Настройка linux сервера в google диске
Validating the guest environment
The presence of a guest environment can be determined by either inspecting system logs emitted to the console while an instance starts up, or by listing the installed packages while connected to the instance.
Installed packages for the guest environment
This table summarizes the packages that should be installed on instances with working guest environments. The command to list installed packages must be run after connecting to the instance, so this check can only be performed if you have access to it.
Note: CoreOS and Container-Optimized OS do not have package managers. Inspect instance console logs or loaded services to determine the status of the guest environment instead.
Operating system | Command to list packages | Expected output |
---|---|---|
CentOS/RHEL | ||
Debian | ||
Ubuntu | ||
SUSE (SLES) | ||
Windows |
Google Compute Engine против Amazon EC2
В сравнении с аналогичным сервисом Amazon EC2 подход Google выглядит значительно менее гибким и существенно упрощенным — но в то же время более шустрым и простым, а обойдётся он чуть-чуть дешевле. Compute Engine — это скорее классическая IaaS-услуга в формате, доступном у немалого числа интернет-провайдеров, и различие между ним и Amazon EC2 столь велико, что выбор с учетом требований конкретного проекта будет весьма простым и очевидным. Так, если требования к IaaS-услуге просты, марка Linux-дистрибутива не очень принципиальна, а сам проект рассчитан преимущественно на быстрый запуск множества виртуальных экземпляров под конкретную и хорошо отработанную задачу с типовой несложной балансировкой, то Google Compute Engine смотрится лучшим решением. Но как только начинается проектная специфика, когда реализуется многоуровневая архитектура, а в перспективе желательно полностью задействовать потенциал смежных облачных сервисов, лучше остановиться на Amazon EC2 — в частности, потому, что документация Google заметно проигрывает конкуренту. Она не слишком понятна, не очень подробна и при этом перенасыщена техническими деталями.
Learn how to create a Linux virtual machine (VM) instance in Compute Engine using the Google Cloud console.
For step-by-step guidance on this task directly in Cloud console, click Guide me:
The following sections take you through the same steps as clicking Guide me.
Разбираемся с ценами
Плата за сервисы Google Compute Engine (рис. 9), в отличие от Amazon EC2, взимается с округлением не до часа, а до минут (с момента старта сервера должно пройти не менее десяти минут). Крохотный вариант micro с ОЗУ 600 Мб, одним виртуальным процессором и без локального диска обойдется в 0,019 долл. в час (в Amazon — на один цент дороже). Чуть более мощный сервер с 1,7 Гб ОЗУ и процессором 1,38 ГГц стоит 0,054 долл. в час (в Amazon — 0,06 долл.). Цена часа работы 16-ядерной машины со 104 Гб ОЗУ приблизится к двум долларам. Дополнительно потребуется выплачивать 10—20 центов за гигабайт исходящего трафика (в зависимости от региона) и услуги балансировщика нагрузки: 0,025 долл. в час за пять правил балансировки плюс один цент за каждое дополнительное правило и 0,008 долл. за гигабайт обработанных данных (трафик запросов). Интересно, что за статический и присвоенный машине IP-адрес деньги не взимаются, а за неиспользуемый будет списываться 0,01 долл. в час.
Отмечу, что львиную долю расходов в нагрузочных интенсивных проектах может “съедать” общий трафик — на него подчас приходится заметно больше половины всех затрат (если месячная стоимость эксплуатации составляет несколько тысяч долларов). Ещё одна интересная особенность: Amazon с первых же дней активно списывала с моего счета доллары, невзирая на формальный статус пробного бесплатного режима (некоторые жизненно важные сервисы наподобие статического IP оказались полностью платными), а вот Google, никак особо тестовый период не рекламируя, за точно такие же эксперименты с её IaaS-сервисом не взяла с меня ни цента.
Создаем аккаунт
С первых шагов может ввести в заблуждение тот факт, что Гугл безапелляционно квалифицирует вас как юридическое лицо без права смены статуса. Это норма с недавних пор и с этим придется смириться. Далее бесстрашно указываем платежные данные, деньги без предупреждения не снимутся, даже когда будет исчерпан бесплатный лимит.
Console
In the Google Cloud console, go to the VM instances page.
- Click the instance you need to examine. or reset the instance.
- Under Logs, click Serial port 1 (console).
- Search for the expected output referencing the table above.
Рис. 9. Окно тарификации текущих сервисов
Expected console logs for the guest environment
This table summarizes expected output for console logs emitted by instances with working guest environments as they start up.
Operating system | Service management | Expected output |
---|---|---|
CentOS/RHEL Debian Ubuntu SLES Container-Optimized OS 89 and newer | systemd | |
Container-Optimized OS 85 and older | systemd | |
Windows |
To view console logs for an instance, follow these steps.
Installing the guest environment
Debian
To update Debian operating systems, run the following commands:
Connect to the VM instance
Connect to an instance by using the Google Cloud console and completing the following steps. You're connected to the VM as the user you used to access the VM instances page.
-
In the Cloud console, go to the VM instances page.
Windows
To update Windows operating systems, run the following command:
1. Создание и настройка Virtual Machine Instances
Страхуемся от эфемерных данных
По умолчанию виртуальному серверу выдается 10 Гб дискового пространства (в схожем сервисе Amazon EC2 — 30 Гб), однако это пространство считается “эфемерным” и фактически предназначено только для типовой загрузки ОС (Scratch boot disk). После любого сбоя или технического обслуживания физических серверов Google все пользовательские настройки (например, дополнительно установленные приложения и конфигурации) пропадут. Надо отметить, что подобное случается крайне редко: Google поддерживает схему “живой миграции”, когда виртуальный сервер “перемещается” внутри ЦОДа или между оными без прерывания собственной работы.
Amazon EC2 предлагает в качестве страховки по умолчанию подключение “долгосрочного” диска самостоятельного сервиса S3, однако за эту услугу будет взиматься дополнительная плата. Аналогичный вариант Google, только непосредственно интегрированный в Google Compute Engine, называется Persistent Disk. Добавление диска в сервер осуществляется из раздела консоли Disks кнопкой New Disk (рис. 7). В окне настройки можно создать пустой диск (поле Source type) и затем присоединить его к виртуальной машине либо выбрать один из трех вышеупомянутых образов Linux, под который устройство хранения будет размечено в качестве загрузочного. В таком случае на первом этапе создания виртуальной машины в поле Boot source (загрузочный диск) выбирается значение Existing persistent disk, а в поле Source Disk — заранее подготовленный диск (рис. 8).
Объём диска задается в поле Size (10 Гб обойдутся в 0,4 долл. в месяц). Над созданным диском доступна единственная операция удаления (кнопка Delete).
5. Настройка File Transfer
У нас загрузочный диск Linux и поэтому доступны четыре способа:
- Использование командной строки gcloud (private SSH keys обязательно)
- Через протокол SFTP в браузере. Это самый простой способ, не требующий SSH key и использующий нативный браузер. Обязательное условие — локальная система у вас Linux или Mac.
- Использование командной строки SDC (private SSH keys обязательно)
- Программа WinSCP для счастливых обладателей Windows (private SSH keys обязательно)
Подробно можно почитать здесь и выбрать наиболее понравившийся способ. У меня на ноутбуке Windows 10, поэтому выбор не богатый. Пойдём не самым простым путём и подробно рассмотрим четвёртый способ.
Для начала необходимо сгенерировать SSH ключи. Скачиваем дистрибутив PuTTY и устанавливаем. С его помощью будем генерить ключи.
- Открываем puttygen.exe. Появится окно, где вы можете сгенерировать ключи.
- Оставляем все параметры по умолчанию кроме поля key comment. В него вводим имя пользователя удаленной системы. Скорее всего это ваш gmail аккаунт. Важно — не вся почта, а только та часть, которая до знака @. Я сначала прочитал инструкцию по диагонали и в итоге убил полчаса на то, чтобы понять, почему WinSCP возвращал ошибку.
- Сохраняем private key — его используем в WinSCP локально.
- Копируем текстовое поле private key (убедитесь, что скопировали полностью весь текст! На скриншоте лишь его часть)
- Идем в гугловские облака и там в "Метаданные --> SSH-ключи" добавляем скопированный ключ.
Осталось совсем немного, самая приятная часть — настроить файл-менеджер WinSCP.
- Скачиваем его здесь
- Настраиваем конфигурацию. Помним, что IP — это наш статический IP удаленной системы. Имя пользователя — аналогично PuTTY.
В дополнительных настройках указываем private key и выставляем галочки как на скриншоте.
Всё! Наша боевая система готова к перевариванию тяжелых сверточных нейросетей и объемных данных.
Дополнительно хочу заметить, что использовать один Instance не очень разумно экономически. Разные задачи требуют разных ресурсов. Можно создать двенадцать виртуалок с разными настройками процессоров, памяти и графики или работать с имейджами. Экспериментируйте и любите данные.
This page describes how to manually install the guest environment for virtual machine (VM) instances that are running custom images on Compute Engine.
In most cases, if you are using VMs that are created using Google-provided public images, you do not need to install a guest environment. For information on when to use the guest environment, see When to manually install or update the guest environment.
Before you manually install the guest environment, use the Validate the guest environment procedure to check if the guest environment is running on your VM. If the guest environment is available on your VM but is outdated, update the guest environment.
Windows
Before you begin, ensure that the version of your operating system is supported.
To install the Windows guest environment, run the following commands in an elevated PowerShell version 3.0 or higher prompt. The Invoke-WebRequest command in the instructions below requires a version of PowerShell higher than 3.0.
Download and install GooGet .
During installation GooGet adds content to the system environment. After installation completes, launch a new PowerShell console or provide the full path to the googet.exe file (C:\ProgramData\GooGet\googet.exe).
Open a new console and add the google-compute-engine-stable repository.
Install the core Windows guest environment packages.
Install the optional Windows guest environment package.
Using the googet command.
To view available packages, run the googet available command.
To view installed packages, run the googet installed command.
To update to the latest package version, run the googet update command.
To view additional commands, run googet help .
Рис. 7. Создание рабочего диска для виртуального сервера
Ubuntu
To update Ubuntu operating systems, run the following commands:
To update SLES operating systems, run the following commands:
Дополнительные возможности
Раздел веб-консоли Snapshots предназначен для создания запасных копий рабочих дисков; Images позволяет выбрать подходящий дистрибутив для виртуальной машины (практически все варианты сводятся к старым и новым версиям Debian и CentOS); Network определяет рабочую подсеть, Metadata предлагает указать справочные сведения в формате ключ — значение для всех серверов проекта. Раздел Zones информирует о планируемых в ЦОДах Google технических работах (рис. 5), Operations показывает историю действий, выполненных над ресурсами Google Compute Engine в рамках текущего проекта. Quotas демонстрирует потенциально доступные пользователю квоты — к примеру, рядовой клиент может задействовать 24 процессора, 5 Тб дискового пространства и семь статических IP-адресов.
Важный сервис Load balancing (балансировщик нагрузки) отслеживает состояние виртуальных машин и перераспределяет клиентские запросы между устойчиво функционирующими серверами. Google предлагает минимально необходимый для такого процесса набор параметров (рис. 6): список серверов, регион, где они расположены, способ перенаправления трафика и критичный процент сбоев, выше которого пул ресурсов должен быть заменен запасным.
Installation methods
There are multiple ways that you can install the guest environment. Choose one of the following options:
Import tool. This is the recommended option. However, keep in mind that the import tool not only installs the guest environment but does other configuration updates as well on the image such as configuring networks, configuring bootloader, and installing Google Cloud CLI. For instructions on how to use the import tool, review Making an image bootable.
The import tool supports a wide variety of operating systems and versions. For more information, see operating system details.
Manual installation. Choose one of the following:
- Connect to your instance using SSH or RDP and install the guest environment in-place
- Clone your boot disk and install the guest environment using a startup script
Manual installation of the guest environment is available for the following operating systems:
- Ubuntu 16.04 or later
- CentOS 7 or later
- SUSE Linux Enterprise Server (SLES) 12 SP4 or later and 15 SP1 or later
- Red Hat Enterprise Linux (RHEL) 7 or later
- Debian 9 or later
- Windows Server 2019
- Windows Server 2016
- Windows Server 2012 R2
- Windows Server Semi Annual Channel Releases
- SQL Server on Windows Server
- Windows bring your own license:
- Windows 8
- Windows 10
What's next
- Work through a tutorial to set up a basic web server on your new instance.
- Work through a getting started tutorial in the Google Cloud console.
- Learn how to create and manage virtual machine instances using the gcloud CLI command-line tool and API.
- Learn more about the Linux images available on Compute Engine.
- Learn how to transfer your files to your instance.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Решение тяжёлых задач машинного обучения на стационарных компьютерах дело неблагодарное и малоприятное. Представьте, что вы на домашнем ноутбуке делаете ансамбль из N нейронных сетей для изучения лесов Амазонки на ноутбуке. Сомнительное удовольствие, тем более, что сейчас есть прекрасный выбор облачных сервисов для этих целей — Amazon Web Services, Google Cloud Platform, Microsoft Azure и прочие. Некоторые даже относительно бесплатны и предоставляют видеокарты.
Мы будем настраивать VM на Google Cloud Platform с нуля. Бонусом — стартовые 300$ на год на один gmail аккаунт. Поехали.
- Создание и настройка Virtual Machine Instances
- Настройка сетевых параметров
- Установка Anaconda и дополнительных пакетов
- Настройка Jupyter Notebook
- Настройка File Transfer
Запускаем виртуальный сервер в облаке Google
Для создания виртуальной машины выбираем в веб-консоли службу Compute Engine и нажимаем кнопку New Instance. В дополнение к типовым настройкам (название сервера, описание, теги и метаданные) можно выбрать зону, где сервер будет работать физически (Европа или США), мощность сервера (рис. 1), при необходимости — заранее подготовленный системный образ и тип ОС. В отличие от конструкторского сервиса Amazon EC2, где доступны десятки различных ОС, включая Windows, Google предлагает весьма ограниченный набор из трех вариантов Linux (рис. 2). Правда, пользователи могут устанавливать и собственные образы большинства ведущих Linux-дистрибутивов.
Чтобы создать рабочий сервер в поле External IP, надо выбрать вариант со статическим IP-адресом; имеется также возможность перенаправления трафика на указанный IP. По умолчанию сервер будет автоматически перезапускаться в случае непредвиденных сбоев, а в ходе технического обслуживания ЦОДов Google виртуальная машина портируется в другой ЦОД (эти режимы можно отключить). После финального нажатия на кнопку Create стартует процесс создания и запуска виртуального сервера, который проходит заметно быстрее аналогичного процесса Amazon, занимая буквально несколько секунд.
В веб-консоли всегда можно просмотреть список сформированных виртуальных машин, по каждой из них узнать статистику загрузки процессора, сетевой и дисковый трафики (рис. 3). Удобна возможность непосредственного просмотра экрана запущенного Linux-сервера (рис. 4).
Кнопки Reboot, Delete и Clone веб-консоли предназначены соответственно для перезагрузки, удаления или создания новой копии виртуального сервера. Помимо этого пользователям доступны командная строка и развитый интерфейс программного управления виртуальными серверами.
CentOS/RHEL
To update CentOS and RHEL operating systems, run the following commands:
Clone boot disk and use startup script
If you cannot connect to an instance to manually install the guest environment, install the guest environment using this procedure, which includes the following steps that can be completed in the Google Cloud console or Cloud Shell.
This method shows the procedure for Linux distributions only. For Windows, use one of the other two installation methods.
Debian
Install the public repo GPG key:
Determine the name of the Debian distro, and create the source list file, /etc/apt/sources.list.d/google-cloud.list :
Update package lists:
Install the guest environment packages:
Restart the instance and inspect its console log to make sure the guest environment loads as it starts back up.
Loaded services for the guest environment
This table summarizes the services that should be loaded on instances with working guest environments. The command to list services must be run after connecting to the instance, so this check can only be performed if you have access to it.
Operating system Command to list services Expected output CentOS/RHEL
DebianUbuntu Container-Optimized OS SLES 12+ Windows Before you begin
-
If you want to use the Google Cloud CLI examples in this guide:
- You can either install local tools or use Cloud Shell.
- Use local tools
- Install the Google Cloud CLI.
- Install the jq command-line JSON processor: you can use this processor to filter gcloud output.
CentOS/RHEL
Determine the version of CentOS/RHEL, and create the source repo file, /etc/yum.repos.d/google-cloud.repo :
Update package lists:
Install the guest environment packages:
Restart the instance and inspect its console log to make sure the guest environment loads as it starts back up.
Создаем Virtual Machine и подбираем параметры
Здесь есть несколько интересных моментов. Графические процессоры есть не во всех зонах. В европейских и западно-азиатских я не нашел, в южно-американских искать не стал, поэтому выбрал восточно-американскую зону. Там их можно хоть восемь настроить с абонентской платой 5000 долларов в час. Усредняем данные и настраиваем восемь процессоров, двадцать гигабайт оперативной памяти и один графический процессор. Всё это удовольствие будет стоить 1 доллар в час.
Операционную систему можно выбрать на любой вкус. Берем понравившийся Linux дистрибутив и выставляем галочки "разрешить траффик". Настройку сети и SSH пропускаем. Их мы настроим дальше. И, наконец, один важный момент, снимите галочку с delete boot disk when instance is deleted. Это сохранит вам нервы, когда начнете создавать имейджи под разные задачи.
CentOS/RHEL
Ensure that the version of your operating system is supported.
Create a new instance to serve as the rescue instance. Name this instance rescue. This rescue instance does not need to run the same Linux OS as the problematic instance. This example uses Debian 9 on the rescue instance.
Stop the problematic instance and create a copy of its boot disk.
Set a variable name for the problematic instance. This makes it easier to reference the instance in later steps.
Replace VM_NAME with the name of the problematic instance.
Stop the problematic instance.
Get the name of the boot disk for the problem instance.
Create a snapshot of the boot disk.
Create a new disk from the snapshot.
Delete the snapshot:
Attach the new disk to the rescue instance and mount the root volume for the rescue instance. Because this procedure only attaches one additional disk, the device identifier of the new disk is /dev/sdb. CentOS/RHEL uses the first volume on a disk as the root volume by default, so the volume identifier should be /dev/sdb1. For custom cases, use lsblk to determine the volume identifier.
Run the following steps on the rescue instance.
Mount the root volume of the new disk.
Create the rc.local script.
Move the rc.local script to the root volume of the new disk and set permissions. Move any existing rc.local script aside. The temporary script will replace it when it finishes.
Un-mount the root volume of the new disk.
Exit the SSH session to the rescue instance.
Detach the new disk from the rescue instance.
Create an instance to serve as the replacement. When you create the replacement instance, specify the new disk as the boot disk. You can create the replacement instance using the Google Cloud Console:
In the Google Cloud console, go to the VM instances page.
Click the problematic instance, then click Create similar.
Specify a name for the replacement instance. In the Boot disk section, click Change, then click Existing Disks. Select the new disk.
Click Create. The replacement instance automatically starts after it is created.
As the replacement instance start up, the temporary rc.local script runs and installs the guest environment. To watch the progress of this script, inspect the console logs for lines emitted by the temporary rc.local script. To view logs, run the following command:
Replace REPLACEMENT_VM_NAME with the name you assigned the replacement instance.
The replacement instance also automatically reboots when the temporary rc.local script finishes. During the second reboot, you can inspect the console log to make sure the guest environment loads.
When you are satisfied that the replacement instance is functional, you can stop or delete the problematic instance.
What's next
- Read the troubleshooting tips.
- Learn more about applying metadata.
- Learn about SSH keys.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Добра всем читающим!
Этот хау-ту размещаю по горячим следам с целью, во-первых, не забыть как делать, а во-вторых, с целью помочь кому-либо создавать инстансы в облаке Google.- App Engine — Сервис для приложений и совместной работы с кодом. Кому интересно документация
- Compute Engine — собственно VPS, диски к ним, файрволл(ы), баласировщики (про них дальше, до сих пор в недоумении почему их два), управление снапшотами и квотами
- Networking — Cloud DNS от Google и VPN
- Storage — облачное хранилищие, хранилище данных и облачный SQL (MySQL)
- BigData — нечто сверхпростое и мне совершенно неясное
Воспользовался разделом Compute Engine, Storage, Networking, Storage.
Разворачивать любую виртуальную машину начинаю с проектирования диска под нее. Ниже скрин:
На скриншоте открыты области, в которых можно создать диск. Нас интересует Европа. Обращаю внимание, указано что датацентр «a» в Европе будет закрыт. Пытливый читатель может поискать расположение центров b,c и d фактически, меня вопрос физического расположения волнует мало.
В моем аккаунте можно создать «Standard Persistent Disk» максимальным размером до 240 Gb. Примитивный тест скорости чтения/записи диска ниже:
Тип исходника для диска (Source Type): Image, Snapshot, Blank соответственно предустановленный образ ОС, из снапшота системы или пустой диск.Лично меня интересовал Debian, кроме него Google предлагает развернуть CentOS, CoreOS, OpenSUSE, Ubuntu, RHEL, Sles и Windows Server 2008.
Создал диск на 10 Гб с Debian Wheezy в области «B» и «C» Europe. Потом в области «C» удалил. Задача состоит в том, чтобы развернуть рабочий сервер и сделать его зеркало. А раз так, то диск в области «C» будем разворачивать из снапшота диска в области «B».
Теперь создаем сам инстанс:
Отмечаем оба варианта, идем дальше — выбираем Exiting Disk и говорим какой из дисков подключить к машине. Надо сказать, что второй диск когда я цеплял к инстансу, то все было сделано «на горячую» — появился /dev/sdb, который я успешно разбил и примонтировал не перезагружая инстанс.
Кстати диск во время удаления инстанса можно удалить: необходимо выделить соответствующий пункт ниже выбора типа диска.
Раздел Networking при создании доступен только IP адрес — внутренняя сеть или прилепим белый IP.
Кстати, ISPanel до сих пор не понимает, что есть Amazon, Google и прочие сервисы, у которых не прописывается IP адрес в настройки сети. Установка и лицензирование панели усложняются ожиданием техподдержки или созданием виртуального интерфейса с нужным ISPanel адресом. Ну неудобно же!
Когда инстанс создан можно зайти в его настройки и увидеть:
И озадачится вопросом: «а как получить доступ по SSH?». Вот собственно я изучал предмет минут 30, вышло следующее:
В блоке управления SSH ключами вводится ключ, сгенерированый, например, PuttyGen.
а) Запускаем
б) нажимаем Generate
в) болтаем мышью
г)получаем ключ
д)меняем Key Comment на имя пользователя
е) Save public key
ж) Save private key — не защищаем паролем файл
з) Copy/Paste из окна в SSH Keys строку вида ssh-rsa ABRAKADABRA dmitryЕсли мы прилепили белый IP, то можно идти авторизовываться именем пользователя в созданном инстансе (в Putty файл ключа указывается в настройках: Connection->SSH->Auth). А можно зайти в консоль через веб-интерфейс из гугла (вверху кнопка SSH). А еще наверное можно настроить VPN из соответствующего раздела для доступа к закрытому серверу, не пробовал.
- Compute Engine — New Snapshot
- обзываем снапшот и выбираем нужный диск
- Create
В дисках создаем новый диск из снапшота в нужном регионе и прикручиваем его к инстансу. На этом клонирование завершено. Заняло 10 минут.
Compute Engine -> Networks -> Default (Network) -> Firewall rules — New
При настройке файрволла руководствуемся здравым смыслом. Синтаксис простой.
Надо сказать, что Google Chrome чудил и минут 30 заводил и не завел ни одно правило. Спас Mozilla, однако заводить правило для файрволла реально долго, около 3 минут у меня заняло.Чтобы создать облачный MySQL — инстанс, оптимизированный для баз данных — идем Storage -> Cloud SQL -> New. Я выбрал второй в списке: 1Gb ОЗУ, 250 Gb диск. Тестировали базу 800Мб — летает. Ну и с инстанса перенатравили ISPanel на «внешний» сервер MySQL.
Получить доступ к базам данных можно из PHP, Phyton, JAVA, console и тп. Приведу пример для PHP:И понаделать пользователей через спец.консоль.
И дать доступы с выбранных инстансов или IP адресов.В консоли управления Cloud SQL через кнопку EDIT можно найти привычные настройки для my.cnf.
По незнанию я создавал Bucket из веб-интерфейса, хотя проще бы было зайти в консоль сервера и создать оттуда. У Google есть API, который предустановлен в инстансах. Я воспользовался gsutil:
Сначала нужно обновится:
Ссылка была на 10 строк, я ее немного сократил. По этой ссылке мы даем доступ от пользователя Google, получаем ID, который вбиваем в verification code:Имеем доступ, в моем случае, к Bucket. Ну или можем создать:
Это я туда файлик закинул.Можем синхронизировать Bucket и каталог системы:
Ну и так далее и тому подобное.Для того, чтобы примонтировать Bucket gs://zp-storage/ как каталог, необходимо воспользоваться парой сторонних утилит:
s3fuse — утилита, которая используется для аналогичных целей, например, для монтирования Amazon S3. Пишут, что с ее помощью можно монтировать Cloud Storage (google), но что-то я не нашел вразумительного конфига хотя бы с комментарием сего действа.
Из пакетов по зависимостям s3fuse не встала, собирал из исходников. Сборка идет ./configure && make && make install, а вот перечень зависимостей:
А вот gcsfs встал из пакета deb.Необходимые изменения в conf-файлах для подключения Google Cloud Storage:
С получением authorization code, который необходимо ввести в строку для создания токена подключения к Storage.
Тут хаутушечке конец, кто открыл хоть один спойлер — молодец.
Большая просьба. Опираясь на предыдущий опыт написания на Habrahabre статей, прошу минусовать обоснованно. Иначе рискую никогда не понять в чем мои недочеты: в стиле изложения, в конкретике, в восприятии и изложении мной информации. За каждый коммент буду слать позитивные лучи.
UPD: Выяснилось что в инстансе Google Cloud закрыта отправка через 25 порт (и коннект к другому серверу по 25 порту). Совсем. Вместо этого предлагается использовать релейный почтовый сервер с отправкой по порту 587.
Ubuntu
Ensure that the version of your operating system is supported
Create a new instance to serve as the rescue instance. Name this instance rescue. This rescue instance does not need to run the same Linux OS as the problematic instance. This example uses Debian 9 on the rescue instance.
Stop the problematic instance and create a copy of its boot disk.
Set a variable name for the problematic instance. This makes it easier to reference the instance in later steps.
Replace VM_NAME with the name of the problematic instance.
Stop the problematic instance.
Get the name of the boot disk for the problem instance.
Create a snapshot of the boot disk.
Create a new disk from the snapshot.
Delete the snapshot:
Attach the new disk to the rescue instance and mount the root volume for the rescue instance. Because this procedure only attaches one additional disk, the device identifier of the new disk is /dev/sdb. Ubuntu labels its root volume 1 by default, so the volume identifier should be /dev/sdb1. For custom cases, use lsblk to determine the volume identifier.
Run the following steps on the rescue instance.
Mount the root volume of the new disk.
Create the rc.local script.
Move the rc.local script to the root volume of the new disk and set permissions. Move any existing rc.local script aside. The temporary script will replace it when it finishes.
Un-mount the root volume of the new disk.
Exit the SSH session to the rescue instance.
Detach the new disk from the rescue instance.
Create a new instance to serve as the replacement. When you create the replacement instance, specify the new disk as the boot disk. You can create the replacement instance using the Google Cloud Console:
In the Google Cloud console, go to the VM instances page.
Click the problematic instance, then click Create similar.
Specify a name for the replacement instance. In the Boot disk section, click Change, then click Existing Disks. Select the new disk.
Click Create. The replacement instance automatically starts after it is created.
As the replacement instance start up, the temporary rc.local script runs and installs the guest environment. To watch the progress of this script, inspect the console logs for lines emitted by the temporary rc.local script. To view logs, run the following command:
Replace REPLACEMENT_VM_NAME with the name you assigned the replacement instance.
The replacement instance also automatically reboots when the temporary rc.local script finishes. During the second reboot, you can inspect the console log to make sure the guest environment loads.
When you are satisfied that the replacement instance is functional, you can stop or delete the problematic instance.
3. Установка Anaconda и дополнительных пакетов
Запускаем созданный Instance, подключаемся через SSH и для установки дистрибутива Анаконды вводим в командной строке:
В конце установки не забудьте ввести "yes", чтобы прописать переменную PATH
Ставим любимые пакеты:И переходим к настройке Jupyter Notebook.
Install the guest environment in-place
Use this method to install the guest environment if you can connect to the target instance using SSH. If you can't connect to the instance to install the guest environment, you can instead install the guest environment by cloning its boot disk and using a startup script.
This procedure is useful for imported images if you can connect using SSH password-based authentication. It might also be used to reinstall the guest environment if you have at least one user account with functional key-based SSH.
Before you begin
-
Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Make sure that billing is enabled for your Cloud project. Learn how to check if billing is enabled on a project.
Ubuntu
Ensure that the version of your operating system is supported.
Enable the Universe repository. Canonical publishes packages for its guest environment to the Universe repository.
Update package lists:
Install the guest environment packages:
Restart the instance and inspect its console log to make sure the guest environment loads as it starts back up.
Ensure that the version of your operating system is supported.
Update package lists:
Install the guest environment packages:
Restart the instance and inspect its console log to make sure the guest environment loads as it starts back up.
Рис. 8. Выбираем рабочий диск на этапе создания виртуального сервера
Clean up
To avoid incurring charges to your Google Cloud account for the resources used on this page, follow these steps.
In the Google Cloud console, go to the VM instances page.
Click the name of the instance you created.
At the top of the instance's details page, click Delete.
Настройка брандмауэра.
Jupyter Notebook — наш главный инструмент и ему будет нужен доступ к виртуальной машине. Создаем правило со следующими параметрами:
- Разрешить входящий трафик
- Указываем любой порт в разумных пределах. К примеру, 22-й не подойдет, на нем висит SSH.
- Диапазон адресов делаем по умолчанию 0.0.0.0/0 (можно поменять)
Мы создали чистую VM и в итоге у вас должно получиться примерно так:
И самое главное — не забывайте выключать VM, когда закончили работу!
Limitations
You can't manually install or use the import tool to install guest environments for Fedora CoreOS and Container-optimized operating systems. If you need one of these operating systems, we recommend that you use public images, because a guest environment is included as a core part of all public images.
Настройка статического IP
По умолчанию внешний IP динамический. Сделаем его статическим и жить сразу станет гораздо проще. При привязке к проекту или виртуальной машине (как раз наш случай) — это бесплатно.
2. Настройка сетевых параметров
gcloud
Use the gcloud compute instances get-serial-port-output subcommand to connect using the Google Cloud CLI. For example:
Replace VM_NAME with the name of the instance you need to examine.
Search for the expected output referencing the table above.
Updating the guest environment
If you are getting a message that the guest environment is outdated, update the packages for your operating system.
4. Настройка Jupyter Notebook
Вводим в командную строку (порт — который вы указали в настройках брандмауэра):
И теперь один интересный момент. Если у вас всё прошло успешно, то после старта Jupiter Server в баше вы увидите примерно это:
Если перейти по ссылке, то в браузере вывалится ошибка авторизации, что совершенно очевидно. Для этого в строке браузера надо явно указать, созданный выше внешний статический IP:
Теперь нам осталось только настроить File Transfer между нашей локальной системой и удаленной. Без этого леса Амазонки не изучить.
Debian
Ensure that the version of your operating system is supported
Create a new instance to serve as the rescue instance. Name this instance rescue. This rescue instance does not need to run the same Linux OS as the problematic instance. This example uses Debian 9 on the rescue instance.
Stop the problematic instance and create a copy of its boot disk.
Set a variable name for the problematic instance. This makes it easier to reference the instance in later steps.
Replace VM_NAME with the name of the problematic instance.
Stop the problematic instance.
Get the name of the boot disk for the problem instance.
Create a snapshot of the boot disk.
Create a new disk from the snapshot.
Delete the snapshot:
Attach the new disk to the rescue instance and mount the root volume for the rescue instance. Because this procedure only attaches one additional disk, the device identifier of the new disk is /dev/sdb. Debian uses the first volume on a disk as the root volume by default, so the volume identifier should be /dev/sdb1. For custom cases, use lsblk to determine the volume identifier.
Run the following steps on the rescue instance.
Mount the root volume of the new disk.
Create the rc.local script.
Move the rc.local script to the root volume of the new disk and set permissions. Move any existing rc.local script aside. The temporary script will replace it when it finishes.
Un-mount the root volume of the new disk.
Exit the SSH session to the rescue instance.
Detach the new disk from the rescue instance.
Create a new instance to serve as the replacement. When you create the replacement instance, specify the new disk as the boot disk. You can create the replacement instance using the Google Cloud Console:
In the Google Cloud console, go to the VM instances page.
Click the problematic instance, then click Create similar.
Specify a name for the replacement instance. In the Boot disk section, click Change, then click Existing Disks. Select the new disk.
Click Create. The replacement instance automatically starts after it is created.
As the replacement instance start up, the temporary rc.local script runs and installs the guest environment. To watch the progress of this script, inspect the console logs for lines emitted by the temporary rc.local script. To view logs, run the following command:
Replace REPLACEMENT_VM_NAME with the name you assigned the replacement instance.
The replacement instance also automatically reboots when the temporary rc.local script finishes. During the second reboot, you can inspect the console log to make sure the guest environment loads.
When you are satisfied that the replacement instance is functional, you can stop or delete the problematic instance.
Create a Linux VM instance
- In the Cloud console, go to the Create an instance page.
Allow a short period of time for the instance to start. After the instance is ready, it's listed on the VM instances page with a green status icon.
Compute Engine grants the user who creates the VM with the roles/compute.instanceAdmin role. Compute Engine also adds that user to the sudo group.
Читайте также:
- Use local tools