AWS RDSを構築しEC2からアクセス

  • 2019.11.19
  • AWS
AWS RDSを構築しEC2からアクセス

はじめに

DB系はどうしても後回しになってしまうのですが、この辺りで軽く勉強をはじめようかと思います。

今回はRDSを構築してEC2インスタンスからアクセスするところまでやります。

EC2インスタンスの構築

EC2インスタンスを構築します。

いつものJSONファイルです。

{
    "ImageId": "ami-0064e711cbc7a825e",
    "InstanceType": "t2.micro",
    "KeyName": "myawskey-tokyo",
    "MaxCount": 1,
    "SecurityGroupIds": [
        "sg-04b4e7642a8fc6efe"
    ],
    "SubnetId": "subnet-0b99e52d17314979d"
}

EC2インスタンスを構築します。直接変数にインスタンスIDとPublicDNSNameをセットするようにしてみました。

$ ins_id=$(aws ec2 run-instances --cli-input-json file://ec2-amazonlinux.json --query Instances[].InstanceId --output text)
$ ins_pubdns=$(aws ec2 describe-instances --filter Name=instance-id,Values=$ins_id --query *[].Instances[].PublicDnsName --output text)

セキュリティグループの作成

VPCは既存のものを使用しますが、RDS接続用のセキュリティグループを作成します。

$ sec_id=$(aws ec2 create-security-group --group-name myrdsgroup --description "RDS Connect" --vpc-id $vpc_id --output text)
$ aws ec2 authorize-security-group-ingress --group-id $sec_id --protocol tcp --port 3306 --cidr 0.0.0.0/0

RDS(MariaDB)の構築

今回はRDSはMariaDBの無料枠で構築していきます。

RDS構築用のJSONファイルを作成します。

{
    "DBName": "TestDB",
    "DBInstanceIdentifier": "testdb-1",
    "AllocatedStorage": 20,
    "DBInstanceClass": "db.t2.micro",
    "Engine": "mariadb",
    "MasterUsername": "admin",
    "MasterUserPassword": "hogehoge",
    "VpcSecurityGroupIds": [
        "sg-0fc1435eb1b8b4cc1"
    ],
    "DBSubnetGroupName": "default-vpc-04e72e6413b624d29",
    "BackupRetentionPeriod": 7,
    "Port":3306,
    "MultiAZ": false,
    "AutoMinorVersionUpgrade": true,
    "PubliclyAccessible": false,
    "StorageType": "gp2",
    "StorageEncrypted": false,
    "CopyTagsToSnapshot": true,
    "DeletionProtection": false,
    "MaxAllocatedStorage": 1000
}

次のコマンドでRDSを構築します。

$ aws rds create-db-instance --cli-input-json file://mariadb.json

構築が完了するまで数分かかります。

$ aws rds describe-db-instances --db-instance-identifier testdb-1 --query DBInstances[].DBInstanceStatus
[
    "available"
]

availableになったら構築完了です。接続用のアドレスを取得しておきます。

$ aws rds describe-db-instances --db-instance-identifier testdb-1 --query DBInstances[].Endpoint
[
    {
        "Address": "testdb-1.hoge.ap-northeast-1.rds.amazonaws.com",
        "Port": 3306,
        "HostedZoneId": "Z24O6O9L7SGTNB"
    }
]

EC2から接続

それではEC2インスタンスからRDSに接続してみます。

$ ssh -i $key ec2-user@$ins_pubdns
The authenticity of host 'ec2-hoge.ap-northeast-1.compute.amazonaws.com (hoge)' can't be established.
ECDSA key fingerprint is SHA256:hoge
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'ec2-hoge.ap-northeast-1.compute.amazonaws.com,hoge' (ECDSA) to the list of known hosts.

       __|  __|_  )
       _|  (     /   Amazon Linux 2 AMI
      ___|\___|___|

https://aws.amazon.com/amazon-linux-2/
16 package(s) needed for security, out of 27 available
Run "sudo yum update" to apply all updates.
[ec2-user@ip-10-1-0-75 ~]$ sudo yum -y install mariadb
読み込んだプラグイン:extras_suggestions, langpacks, priorities, update-motd
amzn2-core                                                                                         | 2.4 kB  00:00:00     
依存性の解決をしています
--> トランザクションの確認を実行しています。
---> パッケージ mariadb.x86_64 1:5.5.64-1.amzn2 を インストール
--> 依存性解決を終了しました。

依存性を解決しました

==========================================================================================================================
 Package                   アーキテクチャー         バージョン                         リポジトリー                  容量
==========================================================================================================================
インストール中:
 mariadb                   x86_64                   1:5.5.64-1.amzn2                   amzn2-core                   9.0 M

トランザクションの要約
==========================================================================================================================
インストール  1 パッケージ

総ダウンロード容量: 9.0 M
インストール容量: 49 M
Downloading packages:
mariadb-5.5.64-1.amzn2.x86_64.rpm                                                                  | 9.0 MB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  インストール中          : 1:mariadb-5.5.64-1.amzn2.x86_64                                                           1/1 
  検証中                  : 1:mariadb-5.5.64-1.amzn2.x86_64                                                           1/1 

インストール:
  mariadb.x86_64 1:5.5.64-1.amzn2                                                                                         

完了しました!
[ec2-user@ip-10-1-0-75 ~]$ mysql -h testdb-1.hoge.ap-northeast-1.rds.amazonaws.com -P 3306 -u admin -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 27
Server version: 10.2.21-MariaDB-log 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.

MariaDB [(none)]> 

接続できました。