0

яндекс практикум

Практическая работа. Начало работы в CLI

26.04.2022

На этой практической работе мы установим утилиту yc, познакомимся с режимом подсказок --help и выполним несколько простых команд. Установка CLI Первым делом скачайте и установите CLI (если вы еще не сделали этого ранее, в первом курсе).Теперь настройте программу для работы с вашим аккаунтом и облаком. Для этого запустите командную строку и введите команду:

yc init 

В консоли появится предложение перейти по ссылке, чтобы программа получила доступ к аккаунту и облаку. Перейдите по ссылке, согласитесь с условиями, затем скопируйте токен и вставьте его в окно консоли.Срок жизни токена — один год. Через год необходимо получить новый токен и повторить аутентификацию.Если кто-то узнал ваш токен, отзовите его и запросите новый.Продолжайте установку: выберите облако, каталог и зоны доступности по умолчанию. Следуйте указаниям системы и завершите настройку.Готово!При установке автоматически создается профиль default, в него записываются выбранные настройки.Список профилей можно посмотреть командой:

yc config profile list 

Флаг –helpНа прошлом уроке вы узнали о флагах, которые используются при запуске команд. Пожалуй, самый важный и частый флаг — --help (сокращенно -h), поэтому поговорим о нём подробнее.Команд для управления ресурсами облака много. Вы запомните некоторые, но помнить всё невозможно. Пользуйтесь флагом --help, когда пишете команду. В этом случае она не выполняется, вместо этого в консоль выводится полная информация о команде: о ресурсах, которыми она управляет, и параметрах запуска.Помните, на предыдущем уроке мы говорили о типичной структуре большинства команд CLI: сервис — ресурс — действие — флаги.Важная особенность флага --help: можно применять его для каждого уровня структуры и писать команду постепенно.Допустим, вы хотите перезапустить ВМ, но не помните полный синтаксис команды.

  1. Сначала вызовите описание сервиса Yandex Compute Cloud:
yc compute --help 

Вы увидите синтаксис команды (раздел Usage), список ресурсов, которыми можно управлять (Groups), действий (Commands) и флагов:

Usage:
  yc compute <group|command>
 
Groups:
  instance               Manage virtual machine instances
  disk                   Manage disks
  disk-type              Show available disk types
  image                  Manage images
  snapshot               Manage snapshots
  zone                   Show availability zones
  instance-group         Manage instance groups
  placement-group        Manage placement groups
  host-type              Show available host types
  host-group             Manage host groups
  disk-placement-group   Manage disk placement groups
 
Commands:
  connect-to-serial-port Connect to serial port
 
Global Flags:
      --profile string       Set the custom configuration file.
      --debug                Debug logging.
      --debug-grpc           Debug gRPC logging. Very verbose, used for debugging connection problems.
      --no-user-output       Disable printing user intended output to stderr.
      --retry int            Enable gRPC retries. By default, retries are enabled with maximum 5 attempts.
                             Pass 0 to disable retries. Pass any negative value for infinite retries.
                             Even infinite retries are capped with 2 minutes timeout.
      --cloud-id string      Set the ID of the cloud to use.
      --folder-id string     Set the ID of the folder to use.
      --folder-name string   Set the name of the folder to use (will be resolved to id).
      --token string         Set the OAuth token to use.
      --format string        Set the output format: text (default), yaml, json, json-rest.
  -h, --help                 Display help for the command. 
  1. Вам нужна ВМ — ресурс instance. Теперь узнайте, как получить список активных ВМ и какая команда отвечает за перезапуск:
yc compute instance --help 

Вы увидите список возможных действий (команд) над ВМ:

Manage virtual machine instances
 
Usage:
  yc compute instance <command>
 
Aliases:
  instances
 
Commands:
  get                      Show information about the specified virtual machine instance
  list                     List virtual machine instances
  create                   Create a virtual machine instance
  create-with-container    Create a virtual machine instance running Docker container
  update                   Update the specified virtual machine instance
  update-container         Update the specified virtual machine instance running Docker container
  add-metadata             Add or update metadata for the specified virtual machine instance
  remove-metadata          Remove keys from metadata for the specified virtual machine instance
  add-labels               Add labels to specified virtual machine instance
  remove-labels            Remove labels from specified virtual machine instance
  delete                   Delete the specified virtual machine instance
  get-serial-port-output   Return the serial port output of the specified virtual machine instance
  stop                     Stop the specified virtual machine instance
  start                    Start the specified virtual machine instance
  restart                  Restart the specified virtual machine instance
  attach-disk              Attach existing disk to the the specified virtual machine instance
  attach-new-disk          Attach new disk to the the specified virtual machine instance
  detach-disk              Detach disk from the the specified virtual machine instance
  update-network-interface Update the specified network interface of virtual machine instance
  add-one-to-one-nat       Add one-to-one NAT to the the specified network interface of virtual machine instance
  remove-one-to-one-nat    Remove one-to-one NAT to the the specified network interface of virtual machine instance
  list-operations          List operations for the specified instance
 
Global Flags:
      --profile string       Set the custom configuration file.
      --debug                Debug logging.
      --debug-grpc           Debug gRPC logging. Very verbose, used for debugging connection problems.
      --no-user-output       Disable printing user intended output to stderr.
      --retry int            Enable gRPC retries. By default, retries are enabled with maximum 5 attempts.
                             Pass 0 to disable retries. Pass any negative value for infinite retries.
                             Even infinite retries are capped with 2 minutes timeout.
      --cloud-id string      Set the ID of the cloud to use.
      --folder-id string     Set the ID of the folder to use.
      --folder-name string   Set the name of the folder to use (will be resolved to id).
      --token string         Set the OAuth token to use.
      --format string        Set the output format: text (default), yaml, json, json-rest.
  -h, --help                 Display help for the command. 
  1. Сначала получите список машин, это команда list:
c compute instance list 

Результатом выполнения команды будет список машин, которые вы создавали в предыдущих курсах, с именами и идентификаторами:

Скопировать код+----------------------+-------------+---------------+---------+----------------+-------------+
|          ID          |    NAME     |    ZONE ID    | STATUS  |  EXTERNAL IP   | INTERNAL IP |
+----------------------+-------------+---------------+---------+----------------+-------------+
| fhm2p20bifmg3k3voda7 | my-instance | ru-central1-a | RUNNING | ХХХ.ХХХ.ХХХ.ХХ | ХХ.ХХХ.Х.ХХ |
+----------------------+-------------+---------------+---------+----------------+-------------+ 
  1. На шаге 2 вы нашли команду перезапуска — restart, теперь можно посмотреть её синтаксис:
yc compute instance restart --help 

Результат выполнения будет таким:

 
Restart the specified virtual machine instance
 
Usage:
  yc compute instance restart <INSTANCE-NAME>|<INSTANCE-ID> [Global Flags...]
 
Flags:
      --id string     Instance id.
      --name string   Instance name.
      --async         Display information about the operation in progress, without waiting for the operation to complete.
 
Global Flags:
      --profile string       Set the custom configuration file.
      --debug                Debug logging.
      --debug-grpc           Debug gRPC logging. Very verbose, used for debugging connection problems.
      --no-user-output       Disable printing user intended output to stderr.
      --retry int            Enable gRPC retries. By default, retries are enabled with maximum 5 attempts.
                             Pass 0 to disable retries. Pass any negative value for infinite retries.
                             Even infinite retries are capped with 2 minutes timeout.
      --cloud-id string      Set the ID of the cloud to use.
      --folder-id string     Set the ID of the folder to use.
      --folder-name string   Set the name of the folder to use (will be resolved to id).
      --token string         Set the OAuth token to use.
      --format string        Set the output format: text (default), yaml, json, json-rest.
  -h, --help                 Display help for the command. 
  1. Наконец, вы получили полный синтаксис команды перезапуска. Примените её к ВМ:
yc compute instance restart --name my-instance 

По такому принципу вы можете сформировать в консоли любую команду.Итак, подведём итоги. Чтобы уточнить синтаксис или порядок действий при работе с CLI, идите одним из трёх путей:

  • найти действие на странице сервиса Yandex.Cloud и там переключиться на вкладку CLI;
  • найти команду в справочнике о yc;
  • с помощью флага --help шаг за шагом уточнять возможности и синтаксис команды.

Синхронный и асинхронный режимы работыНекоторые команды выполняются очень быстро. Например, создание каталога или просмотр настроек профиля. Такие команды можно выполнять подряд, одну за другой — без задержек.Если каждая следующая команда ждёт завершения предыдущей операции, такой режим выполнения называется синхронным. Если какая-то операция в синхронном режиме выполняется долго, CLI выводит в консоли точки, чтобы обозначить, что процесс не завис:

...1s...6s...12s...17s 

Если при выполнении команды ресурс изменяет состояние, создаётся операция. Примеры операций — перезапуск ВМ после обновления или резервное копирование базы данных.Операции порой выполняются довольно долго, а ожидание может затормозить процесс. В таких случаях важно оценить, нужен ли результат операции для выполнения следующих команд. Если нет — можно не ждать завершения операции и сразу же переходить к следующей команде. Такой режим называется асинхронным.Чтобы выполнить команду асинхронно, используйте флаг --async.

  1. Перезапустите одну из ранее созданных ВМ в асинхронном режиме (в команде укажите название вашей ВМ):
yc compute instance restart --name my-instance --async 

В ответ на асинхронный вызов CLI выводит идентификатор операции и информацию о ней:

id: fhm5k7iq03rm2s7enhdk
description: Restart instance
created_at: "2021-03-27T08:32:47.562595036Z"
created_by: aje9cb7k03512mrugcee
modified_at: "2021-03-27T08:32:47.562595036Z"
metadata:
  '@type': type.googleapis.com/yandex.cloud.compute.v1.RestartInstanceMetadata
  instance_id: fhm2p20bifmg3k3voda7 
  1. С помощью идентификатора вы можете проверить результаты выполнения операции:
yc operation get fhm5k7iq03rm2s7enhdk 

Когда операция завершится, вы увидите результат:

id: fhm5k7iq03rm2s7enhdk
...
done: true
... 

Свежие комментарии

Подписка

Лучшие статьи


Fatal error: Uncaught Error: Call to a member function have_posts() on null in /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/inc/blog.php:380 Stack trace: #0 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/widgets/latest-posts/widget.php(257): fox56_blog_grid(NULL, Array) #1 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/widgets/latest-posts/register.php(33): include('/home/host18670...') #2 /home/host1867038/the-devops.ru/htdocs/www/wp-includes/class-wp-widget.php(394): Wi_Widget_Latest_Posts->widget(Array, Array) #3 /home/host1867038/the-devops.ru/htdocs/www/wp-includes/widgets.php(837): WP_Widget->display_callback(Array, Array) #4 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/inc/single.php(417): dynamic_sidebar('sidebar') #5 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/inc/single.php(136): fox56_single_sidebar() #6 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/inc/single.php(7): fox56_single_inner() #7 /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/single.php(23): fox56_single() #8 /home/host1867038/the-devops.ru/htdocs/www/wp-includes/template-loader.php(106): include('/home/host18670...') #9 /home/host1867038/the-devops.ru/htdocs/www/wp-blog-header.php(19): require_once('/home/host18670...') #10 /home/host1867038/the-devops.ru/htdocs/www/index.php(17): require('/home/host18670...') #11 {main} thrown in /home/host1867038/the-devops.ru/htdocs/www/wp-content/themes/fox/inc/blog.php on line 380