Friday, November 12, 2021

gcloud init

 hungnv@Precision-M4800:~/.ssh$ gcloud init

Welcome! This command will take you through the configuration of gcloud.


Your current configuration has been set to: [default]


You can skip diagnostics next time by using the following flag:

  gcloud init --skip-diagnostics


Network diagnostic detects and fixes local network connection issues.

Checking network connection...done.                                                                                                                                  

Reachability Check passed.

Network diagnostic passed (1/1 checks passed).


You must log in to continue. Would you like to log in (Y/n)?  y


Your browser has been opened to visit:


    https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=32555940559.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth&state=2if9qKSA58SiB8jU1vvQGTg1zILv8z&access_type=offline&code_challenge=iGR3H7jmvLYaUppkwr9pWJz7b7PEQvFZVOu7YUW6jpY&code_challenge_method=S256


You are logged in as: [vanhung2210@gmail.com].


Pick cloud project to use: 

 [1] studying-22101989

 [2] Create a new project

Please enter numeric choice or text value (must exactly match list item):  1


Your current project has been set to: [studying-22101989].


Do you want to configure a default Compute Region and Zone? (Y/n)?  y


Which Google Compute Engine zone would you like to use as project default?

If you do not specify a zone via a command line flag while working with Compute Engine resources, the default is assumed.

 [1] us-east1-b

 [2] us-east1-c

 [3] us-east1-d

 [4] us-east4-c

 [5] us-east4-b

 [6] us-east4-a

 [7] us-central1-c

 [8] us-central1-a

 [9] us-central1-f

 [10] us-central1-b

 [11] us-west1-b

 [12] us-west1-c

 [13] us-west1-a

 [14] europe-west4-a

 [15] europe-west4-b

 [16] europe-west4-c

 [17] europe-west1-b

 [18] europe-west1-d

 [19] europe-west1-c

 [20] europe-west3-c

 [21] europe-west3-a

 [22] europe-west3-b

 [23] europe-west2-c

 [24] europe-west2-b

 [25] europe-west2-a

 [26] asia-east1-b

 [27] asia-east1-a

 [28] asia-east1-c

 [29] asia-southeast1-b

 [30] asia-southeast1-a

 [31] asia-southeast1-c

 [32] asia-northeast1-b

 [33] asia-northeast1-c

 [34] asia-northeast1-a

 [35] asia-south1-c

 [36] asia-south1-b

 [37] asia-south1-a

 [38] australia-southeast1-b

 [39] australia-southeast1-c

 [40] australia-southeast1-a

 [41] southamerica-east1-b

 [42] southamerica-east1-c

 [43] southamerica-east1-a

 [44] asia-east2-a

 [45] asia-east2-b

 [46] asia-east2-c

 [47] asia-northeast2-a

 [48] asia-northeast2-b

 [49] asia-northeast2-c

 [50] asia-northeast3-a

Did not print [36] options.

Too many options [86]. Enter "list" at prompt to print choices fully.

Please enter numeric choice or text value (must exactly match list item):  29


Your project default Compute Engine zone has been set to [asia-southeast1-b].

You can change it by running [gcloud config set compute/zone NAME].


Your project default Compute Engine region has been set to [asia-southeast1].

You can change it by running [gcloud config set compute/region NAME].


Created a default .boto configuration file at [/home/hungnv/.boto]. See this file and

[https://cloud.google.com/storage/docs/gsutil/commands/config] for more

information about configuring Google Cloud Storage.

Your Google Cloud SDK is configured and ready to use!


* Commands that require authentication will use vanhung2210@gmail.com by default

* Commands will reference project `studying-22101989` by default

* Compute Engine commands will use region `asia-southeast1` by default

* Compute Engine commands will use zone `asia-southeast1-b` by default


Run `gcloud help config` to learn how to change individual settings


This gcloud configuration is called [default]. You can create additional configurations if you work with multiple accounts and/or projects.

Run `gcloud topic configurations` to learn more.


Some things to try next:


* Run `gcloud --help` to see the Cloud Platform services you can interact with. And run `gcloud help COMMAND` to get help on any gcloud command.

* Run `gcloud topic --help` to learn about advanced features of the SDK like arg files and output formatting

Wednesday, July 10, 2019

Saturday, July 6, 2019

Deployment to Heroku (using Heroku CLI)

//package.json
"scripts": {
 "start":"node path/to/your/app.js"
 },
//app.js
const port = process.env.PORT || 3000
const app = express()
... 
app.listen(port, () => {
 console.log('server up on port ' + port)
})
heroku login
heroku keys:add // add ssh public key to heroku
git init 
git add . 
git commit -m "your comment comes here"
heroku create your-project-name // create a project on heroku
heroku git:remote -a tecknovice-weather-server // add remote branch
heroku buildpacks:set heroku/nodejs //or any another language
git push heroku master //push code from local to remote branch
heroku logs --tail // for real time logging

Tuesday, May 29, 2018

Google Cloud Translate Sample

Java Version

This sample requires you to have Java8.

Download Maven

This sample uses the Apache Maven build system. Before getting started, be sure to download and install it. When you use Maven as described here, it will automatically download the needed client libraries.

Authentication

This sample uses API Key for authentication.
 API Manager > Credentials > Create credentials > API Key
  • Set the environment variable GOOGLE_API_KEY
 export GOOGLE_API_KEY=<YOUR_PROJECT_API_KEY>

 

Download Source code

 
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
cd java-docs-sample/translate

Run the sample

To build the sample, we use Maven.
mvn clean compile assembly:single
We can then run the assembled JAR file with the java command. The variable $COMMAND takes three values langsupport, detect and translate.
JAR_FILE=target/translate-1.0-jar-with-dependencies.jar
java -jar $JAR_FILE <detect|translate|langsupport> <text>
    <optional_source> <optional_target>
Example Usage:
INPUT="A quick brown fox jumped over a lazy dog."
SOURCE_LANG="en"
TARGET_LANG="fr"
Translate API Features:
  • List the languages supported by the API
    java -jar $JAR_FILE langsupport
    
  • List the languages supported for given target language
    java -jar $JAR_FILE langsupport $TARGET_LANG
    
  • Detect input text language
    java -jar $JAR_FILE detect "$INPUT"
    
  • Translate input text (with options)
    java -jar $JAR_FILE translate "$INPUT"
    java -jar $JAR_FILE translate "$INPUT" $SOURCE_LANG $TARGET_LANG
    

Translation API Client Libraries (Java)

Installing the client library

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable.
GCP Console


  1. Go to the Create service account key page in the GCP Console.
    Go to the Create Service Account Key page
  2. From the Service account drop-down list, select New service account.
  3. Enter a name into the Service account name field.
  4. From the Role drop-down list, select Project > Owner.
    Note: The Role field authorizes your service account to access resources. You can view and change this field later using GCP Console. If you are developing a production application, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  5. Click Create. A JSON file that contains your key downloads to your computer.

Enviroment Variables
Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the file path of the JSON file that contains your service account key, and [FILE_NAME] with the filename.

Clone source
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
cd ./java-docs-samples/translate/cloud-client

Build your project with:
mvn clean package -DskipTests
You can then run a given ClassName via:
mvn exec:java -Dexec.mainClass=com.example.translate.ClassName \
    -DpropertyName=propertyValue \
 -Dexec.args="any arguments to the app"

Translate a string (using the quickstart sample)

mvn exec:java -Dexec.mainClass=com.example.translate.QuickstartSample

Quickstart Google Cloud Translation API

This page shows how to make a Google Cloud Translation API request with curl.

Before you begin

  1. Set up a GCP Console project. Set up a project
    Click to:
    • Create or select a project.
    • Enable the Cloud Translation API for that project.
    • Create a service account.
    • Download a private key as JSON.
    You can view and manage these resources at any time in the GCP Console.
  2. Install and initialize the Cloud SDK.
  3. Provide authentication credentials to your application code by running the following command. Replace [PATH] with the location of the JSON file that contains your credentials.
    gcloud auth activate-service-account --key-file=[PATH]

Make a Translation API request

Make a Translation API Request using a REST method call to the v2 translate method.
  1. Use curl to make a request to the https://translation.googleapis.com/language/translate/v2 endpoint.
    The curl command includes JSON with the text to be translated (q), the language to translate from (source), and the language to translate to (target).
    The source and target languages are identified using the iso-639-1 codes. The source language is English (en) and the target language is Spanish (es). The format of the query is noted as "text" for plain text.
    The sample curl command uses the gcloud auth print-access-token command to get an authentication token.
    curl -s -X POST -H "Content-Type: application/json" \
        -H "Authorization: Bearer "$(gcloud auth print-access-token) \
        --data "{
      'q': 'The Great Pyramid of Giza (also known as the Pyramid of Khufu or the
            Pyramid of Cheops) is the oldest and largest of the three pyramids in
            the Giza pyramid complex.',
      'source': 'en',
      'target': 'es',
      'format': 'text'
    }" "https://translation.googleapis.com/language/translate/v2"
      
    You should see a response similar to the following:
    {
      "data": {
        "translations": [
          {
            "translatedText": "La Gran Pirámide de Giza (también conocida como la
             Pirámide de Khufu o la Pirámide de Keops) es la más antigua y más
             grande de las tres pirámides en el complejo de la pirámide de Giza."
          }
        ]
      }
    }
    
      
Congratulations! You've sent your first request to the Cloud Translation API!

Clean up

To avoid unnecessary Google Cloud Platform charges, use the GCP Console to delete your project if you do not need it.

Wednesday, May 23, 2018

Quickstart for Node.js in the App Engine Flexible Environment

This quickstart shows you how to create a small App Engine application that displays a short message.

Before you begin

Before running and deploying this sample, take the following steps:
  1. Use the GCP Console to create a new GCP project, create an App Engine application, and enable billing:
    Go to App Engine When prompted, select the region where you want your App Engine application located and then enable billing.
  2. Install the following prerequisites locally:
    1. Download and install git.
    2. Prepare your environment for Node.js development.
    3. Download and install the Google Cloud SDK and then initialize the gcloud tool:
      Download the SDK
  3. Alternatively: You can use Google Cloud Shell, which comes with git and Cloud SDK already installed, and many other features, such as language support and code editors. After Google Cloud Shell is launched, you can proceed with the rest of this tutorial and execute your commands within Cloud Shell.
This quickstart demonstrates a simple Node.js application written with the Express.js framework.

Download the Hello World app

We've created a simple Hello World app for Node.js so you can quickly get a feel for deploying an app to the App Engine flexible environment. Follow these steps from a command line to download Hello World to your local machine.
Download the sample app and navigate into the app directory:
  1. Clone the Hello World sample app repository to your local machine:
    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
    
    Alternatively, you can download the sample as a zip file and extract it.
  2. Change to the directory that contains the sample code:
    cd nodejs-docs-samples/appengine/hello-world/flexible

Run Hello World on your local machine

  1. Install dependencies for this project by entering the following command:
    npm install
    or if you are using Yarn:
    yarn install
  2. Run the start script.
    npm start
    or if you are using Yarn:
    yarn start
  3. View your app in your web browser:
    • If you are using Cloud Shell, in the toolbar, click Web Preview and select Preview on port 8080 instead.
    • If you are not using Cloud Shell, enter the following address:
      http://localhost:8080
      
You can see the Hello World message from the sample app displayed in the page.
In your terminal window, press Ctrl+C to exit the web server.

Deploy and run Hello World on App Engine

To deploy your app to the App Engine flexible environment:
  1. Deploy the Hello World app by running the following command from the hello-world/flexible directory:
    gcloud app deploy
    Learn about the optional flags.
  2. Launch your browser and view the app at http://YOUR_PROJECT_ID.appspot.com, by running the following command:
    gcloud app browse
This time, the page that displays the Hello World message is delivered by a web server running on an App Engine instance. Congratulations! You've deployed your first Node.js app to App Engine flexible environment!
See the following sections for information about cleaning up as well as links to the possible next steps that you can take.

Clean up

To avoid incurring charges, you can delete your GCP project to stop billing for all the resources used within that project.
  1. In the GCP Console, go to the Projects page. Go to the Projects page
  2. In the project list, select the project you want to delete and click Delete project. After selecting the checkbox next to the project name, click
      Delete project
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

What's next

Learn the whole platform

Now that you know what it's like to develop and deploy App Engine apps, you can stretch out and see the rest of Google Cloud Platform. You already have the Google Cloud SDK installed and that gives you the tools to interact with products like Google Cloud SQL, Google Cloud Storage, Google Cloud Datastore, and more. For a guided walkthrough that teaches you how to create an application that uses the entire platform, not just App Engine, check out our quickstart on creating the Bookshelf app.

Learn about the App Engine flexible environment

Here are some topics to help continue your learning about App Engine.

Hello World code review

Hello World is the simplest possible App Engine app, as it contains only one service, has only one version, and all of the code is located within the app's root directory. This section describes each of the app files in detail.

app.js

The app.js file contains the JavaScript code to start a server and respond to requests.
The following code responds to requests from web clients by displaying the 'Hello World' message, via a server that runs on port 8080.
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.status(200).send('Hello, world!').end();
});
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

app.yaml

The app.yaml file describes an application's deployment configuration:
runtime: nodejsenv: flex
# This sample incurs costs to run on the App Engine flexible environment. 
# The settings below are to reduce costs during testing and are not appropriate
# for production use. For more information, see:
# https://cloud.google.com/appengine/docs/flexible/nodejs/configuring-your-app-with-app-yaml
manual_scaling:  instances: 1resources:  cpu: 1
  memory_gb: 0.5
  disk_size_gb: 10
Here, app.yaml specifies the runtime used by the app, and sets env: flex, specifying that the app uses the flexible environment.

package.json

package.json is used to specify application dependencies, node version, and application startup.
{
  "name": "appengine-hello-world",
  "description": "Simple Hello World Node.js sample for Google App Engine Flexible Environment.",
  "version": "0.0.1",
  "private": true,
  "license": "Apache-2.0",
  "author": "Google Inc.",
  "repository": {
    "type": "git",
    "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
  },
  "engines": {
    "node": ">=4.3.2"
  },
  "scripts": {
    "deploy": "gcloud app deploy",
    "start": "node app.js",
    "lint": "repo-tools lint",
    "pretest": "npm run lint",
    "system-test": "repo-tools test app",
    "test": "npm run system-test",
    "e2e-test": "repo-tools test deploy"
  },
  "dependencies": {
    "express": "4.16.2"
  },
  "devDependencies": {
    "@google-cloud/nodejs-repo-tools": "2.2.1"
  },
  "cloud-repo-tools": {
    "test": {
      "app": {
        "msg": "Hello, world!"
      }
    },
    "requiresKeyFile": true,
    "requiresProjectId": true
  }
}
This package.json specifies that the application uses Node.js v4.3.2 or later, depends on express, and that node app.js is used to start the application. For more details about how your application is installed and run, see the Node.js runtime documentation.