8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GCEの仮想マシンにSSHコマンドで直接接続する

Posted at

gcloudコマンドを使って仮想マシンに接続するには通常 gcloud compute sshを用います:

gcloud compute ssh --project [PROJECT_ID] --zone [ZONE] [INSTANCE_NAME]

このコマンドは追加でSSHのオプションを後につけることが出来ます

gcloud compute ssh [USER@]INSTANCE
 [--command=COMMAND]
 [--container=CONTAINER]
 [--dry-run]
 [--force-key-file-overwrite]
 [--plain]
 [--ssh-flag=SSH_FLAG]
 [--ssh-key-file=SSH_KEY_FILE]
 [--strict-host-key-checking=STRICT_HOST_KEY_CHECKING]
 [--zone=ZONE]
 [--internal-ip     | --tunnel-through-iap]
 [--ssh-key-expiration=SSH_KEY_EXPIRATION     | --ssh-key-expire-after=SSH_KEY_EXPIRE_AFTER]
 [GCLOUD_WIDE_FLAG …]
 [-- SSH_ARGS …]

これ使って例えば8080ポートを転送する場合は

gcloud compute ssh vm_name -- -L 8080:localhost:8080

のようにすることが出来ます。これでVM上でHTTPサーバー等を立ててもSSHトンネル経由で安全に見ることが出来ます。しかしこのオプションを毎回記述するのは面倒ですね。

そこでgcloud compute config-sshというコマンドを使います。これはgcloud compute sshで使っている設定を.ssh/configに書き出すコマンドです。

.ssh/config
# Google Compute Engine Section
#                                                                                                                                                   # The following has been auto-generated by "gcloud compute config-ssh"
# to make accessing your Google Compute Engine virtual machines easier.
#
# To remove this blob, run:
#
#   gcloud compute config-ssh --remove
#
# You can also manually remove this blob by deleting everything from
# here until the comment that contains the string "End of Google Compute
# Engine Section".
#
# You should not hand-edit this section, unless you are deleting it.
#
Host vm_name.region_name.project_name                                                                                                              HostName 12.34.56.78                                                                                                                              IdentityFile /home/myname/.ssh/google_compute_engine
    UserKnownHostsFile=/home/myname/.ssh/google_compute_known_hosts
    HostKeyAlias=compute.123456789
    IdentitiesOnly=yes
    CheckHostIP=no

# End of Google Compute Engine Section

こんな感じのが出力されます。これで

ssh vm_name.region_name.project_name

のように通常のSSHでアクセスすることが出来ます。この設定は(多分)VMの起動時に変化するのでこれを書き換えるのはダメで、追加で設定する場合は

.ssh/config
Host vm_name.region_name.project_name
  LocalForward 8080 localhost:8080

のように同じ名前でもう一つセクションを追記します。もちろんワイルドカード*を使う事も可能です。

8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?