gcloud CLI: A Beginner's Guide

Laboratório 10 minutos universal_currency_alt Sem custo financeiro show_chart Introdutório
info Este laboratório pode incorporar ferramentas de IA para ajudar no seu aprendizado.
Este conteúdo ainda não foi otimizado para dispositivos móveis.
Para aproveitar a melhor experiência, acesse nosso site em um computador desktop usando o link enviado a você por e-mail.

GSP693

Google Cloud self-paced labs logo

Overview

In this hands-on lab, you learn how to connect to computing resources hosted on Google Cloud via gcloud, Google Cloud's CLI tool.

You are encouraged to type the commands themselves, which reinforces the core concepts. This lab uses code blocks that contain the required commands. You can easily copy and paste the commands from the code block into the appropriate places during the lab.

What you'll learn to do

  • Practice using gcloud commands.
  • Connect to compute services hosted on Google Cloud.

Setup and requirements

  • Labs are timed and cannot be paused. The timer starts when you click Start Lab.
  • The included cloud terminal is preconfigured with the gcloud SDK.
  • Use the terminal to execute commands and then click Check my progress to verify your work.

Pre-configured resource:

You have a pre-configured VM instance named gcelab2 in the default network for this lab.

Throughout the lab, you will use the zone:

  • Create an environment variable to store your zone:

    export ZONE={{{project_0.default_zone | ZONE}}}

Task 1. Connecting to your VM instance

gcloud compute makes connecting to your instances easy. The gcloud compute ssh command provides a wrapper around SSH, which takes care of authentication and the mapping of instance names to IP addresses.

SSH stands for Secure Shell. It is a network protocol that allows you to securely access and manage a virtual machine (VM).

  1. To connect to your VM with SSH in a specific zone, run the following command:

    gcloud compute ssh gcelab2 --zone $ZONE

    Output:

    WARNING: The private SSH key file for gcloud does not exist. WARNING: The public SSH key file for gcloud does not exist. WARNING: You do not have an SSH key for gcloud. WARNING: SSH keygen will be executed to generate a key. Generating public/private rsa key pair. Enter passphrase (empty for no passphrase):
  2. In a production environment you should set a passphrase, but for this lab it is not required. Leave the passphrase empty by pressing Enter twice.

  3. You have connected to the virtual machine pre-created for the lab.

    Did you notice how the command prompt changed?

    The prompt now says something similar to sa_xxxxxxxxxxxxxxxxxxxx@gcelab2

    • The reference before the @ sign indicates the account being used.
    • After the @ sign indicates the host machine being accessed.
  4. Install nginx web server on to the virtual machine:

    sudo apt install -y nginx
  5. You don't need to do anything here. To disconnect from SSH and exit the remote shell, run the following command:

    exit

    You should be back at your project's command prompt.

Task 2. Updating the firewall

When using compute resources such as virtual machines, its important to understand the associated firewall rules.

  1. List the firewall rules for the project:

    gcloud compute firewall-rules list

    Output:

    NAME NETWORK DIRECTION PRIORITY ALLOW DENY DISABLED default-allow-icmp default INGRESS 65534 icmp False default-allow-internal default INGRESS 65534 tcp:0-65535,udp:0-65535,icmp False default-allow-rdp default INGRESS 65534 tcp:3389 False default-allow-ssh default INGRESS 65534 tcp:22 False

    From the above you can see the default networks available, where the virtual machine gcelab2 is located.

  2. Try to access the nginx service running on the gcelab2 virtual machine.

    Send HTTP request using cURL to the nginx web server and see if the server responds:

    curl http://$(gcloud compute instances list --filter=name:gcelab2 --format='value(EXTERNAL_IP)')

    The nginx server will not respond and you will see a frozen remote shell. Press Ctrl-c to stop cURL.

    Communication with the virtual machine will fail as it does not have an appropriate firewall rule. Nginx uses port 80 for HTTP traffic by default. The nginx web server is expecting to communicate on tcp:80.

    To get communication working you need to updated a firewall rule which allows incoming traffic on TCP port 80 from any source targeting gcelab2 virtual machine.

  3. Update the firewall rule to allow:

    gcloud compute firewall-rules create default-allow-http --direction=INGRESS --priority=1000 --network=default --action=ALLOW --rules=tcp:80 --source-ranges=0.0.0.0/0 --target-tags=http-server

    Notice --target-tags=http-server in the above command. This firewall rule applies only to instances that have the http-server network tag, which means that incoming traffic on port 80 would be allowed to those instances.

  4. Add the http-server network tag to the gcelab2 virtual machine:

    gcloud compute instances add-tags gcelab2 --tags http-server --zone $ZONE
  5. List the firewall rules for the project:

    gcloud compute firewall-rules list --filter=ALLOW:'80'

    Output:

    NAME NETWORK DIRECTION PRIORITY ALLOW DENY DISABLED default-allow-http default INGRESS 1000 tcp:80 False
  6. List instances that are tagged with the http-server network tag:

    gcloud compute instances list --filter='tags:http-server'

    You can see the 'gcelab2' virtual machine listed.

  7. Verify communication is possible for http to the virtual machine:

    curl http://$(gcloud compute instances list --filter=name:gcelab2 --format='value(EXTERNAL_IP)')

    You can see the default nginx output.

    Click Check my progress to verify the objective. Update the firewall.

Task 3. Viewing the system logs

Viewing logs is essential to understanding how your project works. Use gcloud to access the different logs available on Google Cloud.

  1. View the available logs on the system:

    gcloud logging logs list

    Output:

    NAME: projects/qwiklabs-xxx-xx-xxxxxxxxxxxx/logs/GCEGuestAgent NAME: projects/qwiklabs-xxx-xx-xxxxxxxxxxxx/logs/OSConfigAgent NAME: projects/qwiklabs-xxx-xx-xxxxxxxxxxxx/logs/cloudaudit.googleapis.com%2Factivity NAME: projects/qwiklabs-xxx-xx-xxxxxxxxxxxx/logs/cloudaudit.googleapis.com%2Fdata_access NAME: projects/qwiklabs-xxx-xx-xxxxxxxxxxxx/logs/cloudaudit.googleapis.com%2Fsystem_event NAME: projects/qwiklabs-xxx-xx-xxxxxxxxxxxx/logs/compute.googleapis.com%2Fshielded_vm_integrity NAME: projects/qwiklabs-xxx-xx-xxxxxxxxxxxx/logs/diagnostic-log
  2. View the logs that relate to compute resources:

    gcloud logging logs list --filter="compute"

    Output:

    NAME: projects/qwiklabs-xxx-xx-xxxxxxxxxxxx/logs/compute.googleapis.com%2Fshielded_vm_integrity
  3. Read the logs related to the resource type of gce_instance:

    gcloud logging read "resource.type=gce_instance" --limit 5
  4. Read the logs for a specific virtual machine:

    gcloud logging read "resource.type=gce_instance AND labels.instance_name=gcelab2" --limit 5

Congratulations!

You learned how to launch cloud terminal and run some sample gcloud commands.

Next steps / Learn more

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated January 9, 2024

Lab Last Tested November 12, 2024

Copyright 2026 Google LLC. All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

O laboratório Como proteger aplicativos e recursos do Compute Engine com o Chrome Enterprise Premium não está disponível no momento.

close

Antes de começar

  1. Os laboratórios criam um projeto e recursos do Google Cloud por um período fixo
  2. Os laboratórios têm um limite de tempo e não têm o recurso de pausa. Se você encerrar o laboratório, vai precisar recomeçar do início.
  3. No canto superior esquerdo da tela, clique em Começar o laboratório

Usar a navegação anônima

  1. Copie o nome de usuário e a senha fornecidos para o laboratório
  2. Clique em Abrir console no modo anônimo

Fazer login no console

  1. Faça login usando suas credenciais do laboratório. Usar outras credenciais pode causar erros ou gerar cobranças.
  2. Aceite os termos e pule a página de recursos de recuperação
  3. Não clique em Terminar o laboratório a menos que você tenha concluído ou queira recomeçar, porque isso vai apagar seu trabalho e remover o projeto

Este conteúdo não está disponível no momento

Você vai receber uma notificação por e-mail quando ele estiver disponível

Ótimo!

Vamos entrar em contato por e-mail se ele ficar disponível

Um laboratório por vez

Confirme para encerrar todos os laboratórios atuais e iniciar este

Use a navegação anônima para executar o laboratório

A melhor maneira de executar este laboratório é usando uma janela de navegação anônima ou privada. Isso evita conflitos entre sua conta pessoal e a conta de estudante, o que poderia causar cobranças extras na sua conta pessoal.