# Clean Up Unused IP Addresses - GSP646

## **Overview**

In this lab, you use [Cloud Functions](https://cloud.google.com/functions/) and [Cloud Scheduler](https://cloud.google.com/scheduler/) to identify and clean up wasted cloud resources. On Google Cloud, [static IP addresses are a free resource](https://cloud.google.com/compute/pricing#ipaddress) when they’re attached to a load balancer or virtual machine (VM) instance. When a static IP address is reserved, but not used, it accumulates an hourly charge. In apps that heavily depend on static IP addresses and large-scale dynamic provisioning, this waste can become significant over time.

### What you'll do

*   Create a Compute Engine VM with a static external IP address and a separate unused static external IP address
    
*   Deploy a Cloud Function to identify unused addresses
    
*   Create a Cloud Scheduler job to schedule the function to run by using an HTTP trigger
    

## **Architecture**

The following diagram describes the architecture used in the first section of this lab, where you schedule a Cloud Function to identify and clean up unused IP addresses.

![Architecture diagram](https://cdn.qwiklabs.com/vOeds0SfNS4REZTMX1sSrX%2B15NIDnFMjDEa732h35lI%3D align="left")

## **Setup and requirements**

In this section, you configure the infrastructure and identities required to complete the lab.

### Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click **Start Lab**, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

*   Access to a standard internet browser (Chrome browser recommended).
    

**Note:** Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.

*   Time to complete the lab---remember, once you start, you cannot pause a lab.
    

**Note:** If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

### How to start your lab and sign in to the Google Cloud console

1.  Click the **Start Lab** button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the **Lab Details** panel with the following:
    
    *   The **Open Google Cloud console** button
        
    *   Time remaining
        
    *   The temporary credentials that you must use for this lab
        
    *   Other information, if needed, to step through this lab
        
2.  Click **Open Google Cloud console** (or right-click and select **Open Link in Incognito Window** if you are running the Chrome browser).
    
    The lab spins up resources, and then opens another tab that shows the **Sign in** page.
    
    ***Tip:*** Arrange the tabs in separate windows, side-by-side.
    
    **Note:** If you see the **Choose an account** dialog, click **Use Another Account**.
    
3.  If necessary, copy the **Username** below and paste it into the **Sign in** dialog.
    
    ```apache
    student-04-69795a0a9e28@qwiklabs.net
    ```
    
    You can also find the **Username** in the **Lab Details** panel.
    
4.  Click **Next**.
    
5.  Copy the **Password** below and paste it into the **Welcome** dialog.
    
    ```apache
    MvntOHifhlBQ
    ```
    
    You can also find the **Password** in the **Lab Details** panel.
    
6.  Click **Next**.
    
    **Important:** You must use the credentials the lab provides you. Do not use your Google Cloud account credentials.
    
    **Note:** Using your own Google Cloud account for this lab may incur extra charges.
    
7.  Click through the subsequent pages:
    
    *   Accept the terms and conditions.
        
    *   Do not add recovery options or two-factor authentication (because this is a temporary account).
        
    *   Do not sign up for free trials.
        

After a few moments, the Google Cloud console opens in this tab.

**Note:** To view a menu with a list of Google Cloud products and services, click the **Navigation menu** at the top-left.

![Navigation menu icon](https://cdn.qwiklabs.com/nUxFb6oRFr435O3t6V7WYJAjeDFcrFb16G9wHWp5BzU%3D align="left")

### Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

1.  Click **Activate Cloud Shell**
    
    ![Activate Cloud Shell icon](https://cdn.qwiklabs.com/ep8HmqYGdD%2FkUncAAYpV47OYoHwC8%2Bg0WK%2F8sidHquE%3D align="left")
    
    at the top of the Google Cloud console.
    

When you are connected, you are already authenticated, and the project is set to your **Project\_ID**, `qwiklabs-gcp-01-4d5d311f6ff0`. The output contains a line that declares the **Project\_ID** for this session:

```apache
Your Cloud Platform project in this session is set to qwiklabs-gcp-01-4d5d311f6ff0
```

`gcloud` is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

2.  (Optional) You can list the active account name with this command:
    

```apache
gcloud auth list
```

3.  Click **Authorize**.
    

**Output:**

```apache
ACTIVE: *
ACCOUNT: student-04-69795a0a9e28@qwiklabs.net

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
```

4.  (Optional) You can list the project ID with this command:
    

```apache
gcloud config list project
```

**Output:**

```apache
[core]
project = qwiklabs-gcp-01-4d5d311f6ff0
```

**Note:** For full documentation of `gcloud`, in Google Cloud, refer to [the gcloud CLI overview guide](https://cloud.google.com/sdk/gcloud).

## **Task 1. Enable APIs and clone repository**

1.  In Cloud Shell, enable the Cloud Scheduler API:
    
    ```apache
    gcloud services enable cloudscheduler.googleapis.com
    ```
    
    **Note**: It takes for a while to enable the Cloud Scheduler API.
    

Click **Check my progress** to verify the objective.

Enable the Cloud Scheduler API

**Check my progress**

2.  Clone the repository:
    
    ```apache
    git clone https://github.com/GoogleCloudPlatform/gcf-automated-resource-cleanup.git && cd gcf-automated-resource-cleanup/
    ```
    
3.  Set environment variables and make the repository folder your $WORKDIR where you run all commands related to this lab:
    
    ```apache
    export PROJECT_ID=$(gcloud config list --format 'value(core.project)' 2>/dev/null)
    export region=us-east4
    WORKDIR=$(pwd)
    ```
    

## **Task 2. Create IP addresses**

1.  In Cloud Shell, navigate to the unused-ip directory:
    
    ```apache
    cd $WORKDIR/unused-ip
    ```
    
2.  Export the names of the IP addresses as variables:
    
    ```apache
    export USED_IP=used-ip-address
    export UNUSED_IP=unused-ip-address
    ```
    
3.  Create two static IP addresses:
    
    ```apache
    gcloud compute addresses create $USED_IP --project=$PROJECT_ID --region=us-east4
    gcloud compute addresses create $UNUSED_IP --project=$PROJECT_ID --region=us-east4
    ```
    
    This lab uses the `us-east4` region, but you can choose a different region and refer to it consistently throughout the rest of the lab.
    
4.  Confirm that two addresses were created:
    
    ```apache
    gcloud compute addresses list --filter="region:(us-east4)"
    ```
    
    In the output, a status of RESERVED means that the IP addresses aren’t in use:
    
    ```apache
    NAME       ADDRESS/RANGE  TYPE      PURPOSE  NETWORK  REGION       SUBNET  STATUS
    unused-ip-address  35.232.144.85  EXTERNAL                    us-east4          RESERVED
    used-ip-address    104.197.56.87  EXTERNAL                    us-east4          RESERVED
    ```
    

Click **Check my progress** to verify the objective.

Create two static IP addresses

**Check my progress**

5.  Set the used IP address as an environment variable:
    
    ```apache
    export USED_IP_ADDRESS=$(gcloud compute addresses describe $USED_IP --region=us-east4 --format=json | jq -r '.address')
    ```
    

## **Task 3. Create a VM**

1.  In Cloud Shell, create an instance:
    
    ```apache
    gcloud compute instances create static-ip-instance \
    --zone=us-east4-c \
    --machine-type=e2-medium \
    --subnet=default \
    --address=$USED_IP_ADDRESS
    ```
    

Click **Check my progress** to verify the objective.

Create an instance with static IP address created earlier.

**Check my progress**

2.  Confirm that one of the IP addresses is now in use:
    
    ```apache
    gcloud compute addresses list --filter="region:(us-east4)"
    ```
    
    The output is similar to the following:
    
    ```apache
    NAME       ADDRESS/RANGE  TYPE      PURPOSE  NETWORK  REGION       SUBNET  STATUS
    unused-ip-address  35.232.144.85  EXTERNAL                    us-east4          RESERVED
    used-ip-address    104.197.56.87  EXTERNAL                    us-east4          IN_USE
    ```
    

## **Task 4. Review the Cloud Function code**

*   In Cloud Shell, output the main section of the code:
    
    ```apache
    cat $WORKDIR/unused-ip/function.js | grep "const compute" -A 31
    ```
    

The output is as follows:

```javascript
    const compute = new Compute();
    compute.getAddresses(function(err, addresses){ // gets all addresses across regions
        if(err){
            console.log("there was an error: " + err);
        }
        if (addresses == null) {
            console.log("no addresses found");
            return;
        }
        console.log("there are " + addresses.length + " addresses");

        // iterate through addresses
        for (let item of addresses){

            // get metadata for each address
            item.getMetadata(function(err, metadata, apiResponse) {

                // if the address is not used:
                if (metadata.status=='RESERVED'){

                    // compute age by convering ISO 8601 timestamps to Date
                    var creationDate = new Date(metadata.creationTimestamp);
                    var currDate = new Date();
                    var addressAge = Math.floor((currDate - creationDate)/86400e3);;

                    // delete address
                    item.delete(function(err, operation, apiResponse2){
                        if (err) {
                            console.log("could not delete address: " + err);
                        }
                    })
                }
```

In the preceding code sample, the following is important:

*   `compute.getAddresses(function(err, addresses)` uses the getAddresses method to retrieve IP addresses across all regions in the project.
    
*   `item.getMetadata(function(err, metadata, apiResponse)` gets the metadata for each IP address and checks its STATUS field.
    
*   `if ((metadata.status=='RESERVED') & (calculateAge(metadata.creationTimestamp) >= ageToDelete)){` checks whether the IP address is in use, calculates its age by using a helper function, and compares its age against a constant (set to 0 for the purposes of the lab).
    
*   `item.delete(function(err, operation, apiResponse2){` deletes the IP address.
    

## **Task 5. Deploy the Cloud Function**

1.  Disable the Cloud Functions API:
    
    ```apache
    gcloud services disable cloudfunctions.googleapis.com
    ```
    
2.  Re-enable the Cloud Functions API:
    
    ```apache
    gcloud services enable cloudfunctions.googleapis.com
    ```
    
3.  Add the `artifactregistry.reader` permission for your appspot service account. Replace **\[PROJECT\_ID\]** with your qwiklabs Project ID.
    
    ```apache
    gcloud projects add-iam-policy-binding [PROJECT_ID] \
    --member="serviceAccount:[PROJECT_ID]@appspot.gserviceaccount.com" \
    --role="roles/artifactregistry.reader"
    ```
    
4.  In Cloud Shell, deploy the Cloud Function:
    
    ```apache
    gcloud functions deploy unused_ip_function --trigger-http --runtime=nodejs12 --region=us-east4
    ```
    
    *   If prompted, enter **Y** to allow unauthenticated invocations.
        
    
    **Note:** Deploying a cloud function can take 2-5 minutes, depending on region.
    

Click **Check my progress** to verify the objective.

Deploy cloud function

**Check my progress**

2.  Set the trigger URL as an environment variable:
    
    ```apache
    export FUNCTION_URL=$(gcloud functions describe unused_ip_function --region=us-east4 --format=json | jq -r '.httpsTrigger.url')
    ```
    

## **Task 6. Schedule and test the Cloud Function**

1.  In Cloud Shell, create an *App Engine app* to use Cloud Scheduler:
    
    ```apache
    gcloud app create --region us-east4
    ```
    
2.  In Cloud Shell, create a Cloud Scheduler task to run the Cloud Function at 2 AM every night:
    
    ```apache
    gcloud scheduler jobs create http unused-ip-job \
    --schedule="* 2 * * *" \
    --uri=$FUNCTION_URL \
    --location=us-east4
    ```
    

Click **Check my progress** to verify the objective.

Create App Engine Application

**Check my progress**

3.  Test the job by manually triggering it:
    
    ```apache
    gcloud scheduler jobs run unused-ip-job \
    --location=us-east4
    ```
    

You should receive no output.

Click **Check my progress** to verify the objective.

Run a cloud scheduler job

**Check my progress**

4.  Confirm that the unused IP address was deleted:
    
    ```apache
    gcloud compute addresses list --filter="region:(us-east4)"
    ```
    

The output is similar to the following:

```apache
NAME     ADDRESS/RANGE  TYPE      PURPOSE  NETWORK  REGION       SUBNET  STATUS
used-ip-address  104.197.56.87  EXTERNAL                    us-east4          IN_USE
```

Click **Check my progress** to verify the objective.

Confirm the deletion of unused IP address

* * *

## Solution of Lab

<iframe type="youtube" src="https://www.youtube.com/watch?v=fRCf1XEpqf4" data-node-type="hn-embed"></iframe>

```apache
curl -LO raw.githubusercontent.com/ePlus-DEV/storage/refs/heads/main/labs/GSP646/lab.sh
source lab.sh
```

**Script Alternative**

```plaintext
curl -LO https://raw.githubusercontent.com/Itsabhishek7py/GoogleCloudSkillsboost/refs/heads/main/Clean%20Up%20Unused%20IP%20Addresses/drabhishek.sh
sudo chmod +x drabhishek.sh
./drabhishek.sh
```
