Skip to main content

Perform Foundational Infrastructure Tasks in Google Cloud: Challenge Lab [GSP315]




Link to the video: https://youtu.be/ypbGzTmMUb4

STEPS

Task 1

Go to cloud storage

Make a bucket with the bucket name given <Bucket Name>


Task 2

GO TO PUB/SUB 

Name = <Topic Name>


Task 3

GO TO CLOUD FUNCTIONS

create cloud functions

name = <Cloud Function Name>

region = us-east1

Trigger type = cloud storage

Event type = Finalize/create

Select the bucket you made earlier

done

next

entry point = thumbnail


index.js:


/* globals exports, require */

//jshint strict: false

//jshint esversion: 6

"use strict";

const crc32 = require("fast-crc32c");

const { Storage } = require('@google-cloud/storage');

const gcs = new Storage();

const { PubSub } = require('@google-cloud/pubsub');

const imagemagick = require("imagemagick-stream");

exports.thumbnail = (event, context) => {

  const fileName = event.name;

  const bucketName = event.bucket;

  const size = "64x64"

  const bucket = gcs.bucket(bucketName);

  const topicName = "REPLACE_WITH_YOUR_TOPIC ID";

  const pubsub = new PubSub();

  if ( fileName.search("64x64_thumbnail") == -1 ){

    // doesn't have a thumbnail, get the filename extension

    var filename_split = fileName.split('.');

    var filename_ext = filename_split[filename_split.length - 1];

    var filename_without_ext = fileName.substring(0, fileName.length - filename_ext.length );

    if (filename_ext.toLowerCase() == 'png' || filename_ext.toLowerCase() == 'jpg'){

      // only support png and jpg at this point

      console.log(`Processing Original: gs://${bucketName}/${fileName}`);

      const gcsObject = bucket.file(fileName);

      let newFilename = filename_without_ext + size + '_thumbnail.' + filename_ext;

      let gcsNewObject = bucket.file(newFilename);

      let srcStream = gcsObject.createReadStream();

      let dstStream = gcsNewObject.createWriteStream();

      let resize = imagemagick().resize(size).quality(90);

      srcStream.pipe(resize).pipe(dstStream);

      return new Promise((resolve, reject) => {

        dstStream

          .on("error", (err) => {

            console.log(`Error: ${err}`);

            reject(err);

          })

          .on("finish", () => {

            console.log(`Success: ${fileName} → ${newFilename}`);

              // set the content-type

              gcsNewObject.setMetadata(

              {

                contentType: 'image/'+ filename_ext.toLowerCase()

              }, function(err, apiResponse) {});

              pubsub

                .topic(topicName)

                .publisher()

                .publish(Buffer.from(newFilename))

                .then(messageId => {

                  console.log(`Message ${messageId} published.`);

                })

                .catch(err => {

                  console.error('ERROR:', err);

                });

          });

      });

    }

    else {

      console.log(`gs://${bucketName}/${fileName} is not an image I can handle`);

    }

  }

  else {

    console.log(`gs://${bucketName}/${fileName} already has a thumbnail`);

  }

};


 

package.json:


{

  "name": "thumbnails",

  "version": "1.0.0",

  "description": "Create Thumbnail of uploaded image",

  "scripts": {

    "start": "node index.js"

  },

  "dependencies": {

    "@google-cloud/pubsub": "^2.0.0",

    "@google-cloud/storage": "^5.0.0",

    "fast-crc32c": "1.0.4",

    "imagemagick-stream": "4.1.1"

  },

  "devDependencies": {},

  "engines": {

    "node": ">=4.3.2"

  }

}



Download this image: https://storage.googleapis.com/cloud-training/gsp315/map.jpg  

put it in your bucket after deployment of cloud function


GO TO IAM

remove username 2




Congratulations You have completed the Challenge Lab!

SAKURA SATIO



Comments

Popular posts from this blog

A Tour of Google Cloud Hands-on Labs [GSP282]

Link to the Lab:  https://www.cloudskillsboost.google/focuses/2794?parent=catalog Link to the Video:  https://youtu.be/KFjyI-o60W8 Link to the Channel:  https://www.youtube.com/channel/UCiWP5KYh4MWj-yp3j-DMIrA Answers are marked bold and are highlighted in light yellow This builds a temporary environment in Google Cloud. Start lab (button) Credit Time Score When the timer reaches 00:00:00, you will lose access to your temporary Google Cloud environment. False True Some labs have tracking, which scores your completion of hands-on lab activities. False True In order to receive completion credit for a lab that has tracking, you must complete the required hands-on lab activities. False True What field is NOT found in the left pane? Project ID System admin Password Open Google Console The username in the left panel, which resembles googlexxxxxx_student@qwiklabs.net, is a Cloud IAM identity. True False An organizing entity for anything you build with Google Cloud. Password...

Insights from Data with BigQuery: Challenge Lab [GSP787]

Link to the Lab:  https://www.cloudskillsboost.google/focuses/11988?parent=catalog Link to the Video:  https://youtu.be/jdZd834oysE Link to the Channel:  https://www.youtube.com/channel/UCiWP5KYh4MWj-yp3j-DMIrA STEPS 1.     In the Cloud Console, navigate to Menu > BigQuery . 2.     Click + ADD DATA > Explore public datasets from the left pane. 3.     Search covid19_open_data and then select COVID-19 Open Data 4.     Use Filter to locate the table covid19_open_data under the covid19_open_data dataset. Query 1: Total Confirmed Cases SELECT    SUM ( cumulative_confirmed ) AS total_cases_worldwide FROM    `bigquery-public-data.covid19_open_data.covid19_open_data` WHERE    date = "2020-04-15" Query 2: Worst Affected Areas with deaths_by_states as ( SELECT subregion1_name as state, sum ( cumulative_deceased ) as death_count FROM `bigquery-public-data.covid19_open_data.covid19_open_da...

Ensure Access & Identity in Google Cloud: Challenge Lab [GSP342]

Link to the Lab:  https://www.cloudskillsboost.google/focuses/14572?parent=catalog Link to the Video:  https://www.youtube.com/embed/vVvE-dvGs-Y Link to the Channel:  https://www.youtube.com/channel/UCiWP5KYh4MWj-yp3j-DMIrA STEPS Task 1: gcloud config set compute/zone us-east1-b nano role-definition.yaml *insert whatever is given below* title: "orca_storage_update" description: "Permissions" stage: "ALPHA" description: "Permissions" stage: "ALPHA" includedPermissions: - storage.buckets.get - storage.objects.get - storage.objects.list - storage.objects.update - storage.objects.create   To save a .yaml file press ctrl+x then press y then press enter   gcloud iam service-accounts create orca-private-cluster-sa --display-name "Orca Private Cluster Service Account"   gcloud iam roles create orca_storage_update \ --project $DEVSHELL_PROJECT_ID \ --file role-definition.yaml Task 2 and 3:   gcloud projects add-iam-policy-bi...