LoginSignup
0
0

[ECS・RDS] AWS CLIを利用して、ECSコンテナからRDSに接続するで!!!

Posted at

はじめに

  • この記事は紆余曲折し、エラーを解消しながらゴールまで突き進む物語です
  • 最短の手順だけを述べたものではありません
  • 少しでも皆さんのデバッグのヒントになればと思っております

目的

掲題の実現

前提

  • AWS CLI セットアップ済み
  • ECS構築済み
  • RDS構築済み
    • 今回はMySQLを利用します
  • aws-vault設定済み(どちらでも可)

Systems Managerのパラメータストアに環境変数を用意

パラメータストアにRDSへの接続に必要な環境変数を用意します

自分のパラメータ_-AWS_Systems_Manager-_パラメータストア.png
MySQLですと、上記の環境変数を用意します
ホストには作成したRDSのエンドポイントを設定してください

タスク定義でアプリケーションコンテナがパラメータストアから環境変数を参照するようにしておきましょう

AWS CLIでECSにログインしましょう

以下、コマンドを実行します

❯ aws-vault exec sotaheavymetal21 -- aws ecs execute-command \
    --cluster sota-dev-cluster \
    --task 00000000000000000000000000 \
    --container app \
    --interactive \
    --command "/bin/sh"

The Session Manager plugin was installed successfully. Use the AWS CLI to start a session.


Starting session with SessionId: ecs-execute-command-00000000000000000000000
#

問題なくアプリケーションコンテナにログインできました

続いて以下のコマンドを実行します

apt-get update && apt install -y default-mysql-client

MySQLに接続するためには、まずdefault-mysql-clientパッケージをインストールする必要があります
このパッケージには、MySQLに対するクエリを実行するためのクライアントツールが含まれています
具体的には、apt-get updateコマンドを使用してパッケージリストを最新の状態に更新し、
その後にapt install -y default-mysql-clientコマンドを実行してdefault-mysql-clientパッケージをインストールします
インストールが完了すると、MySQLに接続するための準備が整います

接続には、以下のコマンドを実行します

mysql -h hostname -u username -p database_name
  • hostname:MySQLサーバーのホスト名またはIPアドレス(今回はDBインスタンスのエンドポイント)
  • username:MySQLユーザー名
  • database_name:接続するデータベース名
# mysql -h sotaheavymetal21_rds.ap-northeast-1.rds.amazonaws.com -u sotaheavymetal21 -p sotaheavymetal21_db
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 2021
Server version: 8.0.35 Source distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [sotaheavymetal21_db]>

接続を確立すると、MySQLクライアントが起動し、SQLクエリを実行することができます!

おわりに

お疲れ様でした!!
試行錯誤しながらの記事になっております
少しでも皆さんのお力添えになればと思っています🐰

参考

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