LoginSignup
4
4

データベースクライアントツールから多段SSHでデータベースに接続したい

Last updated at Posted at 2020-11-18

やりたいこと

image.png

こんな感じの踏み台が複数ある多段のSSHでデータベースに接続しに行く構成で、
手元のWindows 10クライアントにインストールしたデータベースクライアントツール(Oracle SQL DeveloperとかMySQL Workbench)から直接DBを見に行きたい。

SSHポートフォワーディング

データベースクライアントツールからは一段までしか踏み台ができないため、SSHポートフォワーディングを実行して、ローカルクライアントのポートをデータベースに間接的に接続します。

便宜的に各サーバの接続情報を定義します。

ホスト IPアドレス/ドメイン ポート
EC2(Bastion) AAA.AAA.AAA.10 22
EC2(Web/AP) BBB.BBB.BBB.11 22
RDS(Oracle) oracle.xxxxxxxxx.ap-northeast-1.rds.amazonaws.com 1521
RDS(MySQL) mysql.xxxxxxxxx.ap-northeast-1.rds.amazonaws.com 3306

ユーザーディレクトリ直下に.sshフォルダを作成。
中にポートフォワードの設定ファイルを作成します。

.ssh\config
Host bastion
  hostname AAA.AAA.AAA.10
  port 22
  user ec2-user
  IdentityFile C:\Users\hoge\.ssh\bastion.pem

Host webap/oracle
  hostname BBB.BBB.BBB.11
  port 22
  user ec2-user
  IdentityFile C:\Users\hoge\.ssh\webap.pem
  ProxyCommand C:\Windows\System32\OpenSSH\ssh.exe bastion -W %h:%p
  GatewayPorts yes
  LocalForward 51521   oracle.xxxxxxxxx.ap-northeast-1.rds.amazonaws.com:1521
  ServerAliveInterval 60
  ServerAliveCountMax 3

Host webap/mysql
  hostname BBB.BBB.BBB.11
  port 22
  user ec2-user
  IdentityFile C:\Users\hoge\.ssh\webap.pem
  ProxyCommand C:\Windows\System32\OpenSSH\ssh.exe bastion -W %h:%p
  GatewayPorts yes
  LocalForward 53306   mysql.xxxxxxxxx.ap-northeast-1.rds.amazonaws.com:3306
  ServerAliveInterval 60
  ServerAliveCountMax 3

パスワード認証の時はIdentityFileの行は指定しなくて大丈夫です。

ssh webap/oraclessh webap/mysqlでポートフォワーディングした先のWeb/APサーバーにSSH接続が成功すればひとまずOK。

>ssh webap/oracle
The authenticity of host 'BBB.BBB.BBB.11 (<no hostip for proxy command>)' can't be established.
ECDSA key fingerprint is SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'BBB.BBB.BBB.11' (ECDSA) to the list of known hosts.
Last login: Wed Nov 18 20:13:03 2020 from ip-BBB-BBB-BBB-11.ap-northeast-1.compute.internal
       __|  __|_  )
       _|  (     /   Amazon Linux 2 AMI
      ___|\___|___|
https://aws.amazon.com/amazon-linux-2/
[ec2-user@ ~]$

上記のコマンドでデータベースへの経路を確立していないとクライアントツールから接続できないので、使うときはターミナルから事前に接続して開きっぱなしにしておきましょう。

クライアントツールからデータベースに接続

ポートフォワーディングしたローカルポートから接続します。

Oracle SQL Developer

.png

MySQL Workbench

image.png

その他、余談

多段じゃなくて踏み台から直接DB接続できる時のconfigの書き方

.ssh\config
Host webapp/mysql
  hostname AAA.AAA.AAA.10
  IdentityFile C:\Users\hoge\.ssh\bastion.pem
  user ec2-user
  port 22
  GatewayPorts yes
  LocalForward 53306   mysql.xxxxxxxxx.ap-northeast-1.rds.amazonaws.com:3306

ポートフォワーディングした状態でローカルのDockerコンテナから接続したい

localhostじゃなくてhost.docker.internalを指定しましょう。

4
4
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
4
4