やりたいこと
こんな感じの踏み台が複数ある多段の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
フォルダを作成。
中にポートフォワードの設定ファイルを作成します。
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/oracle
やssh 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
MySQL Workbench
その他、余談
多段じゃなくて踏み台から直接DB接続できる時の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
を指定しましょう。