0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VSCode Remote-SSH + AWS CLIでEC2を「ローカルフォルダ」として扱う

0
Posted at

背景

マネジメントコンソールでのポチポチ操作から、AWS CLI + VSCode Remote-SSH + Gitの組み合わせに移行した記録です。EC2をあたかも自分のPCのフォルダのように扱えるようになります。

1. EC2起動はコマンド一発

aws ec2 run-instances \
  --image-id ami-0dafcef159a1fc745 \
  --instance-type t2.micro \
  --key-name my-ec2-key \
  --security-group-ids sg-xxxxxxxxx \
  --subnet-id subnet-xxxxxxxxx \
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=MyDevServer}]'

パブリックIPの取得も1コマンドです。

aws ec2 describe-instances \
  --filters "Name=tag:Name,Values=MyDevServer" \
  --query 'Reservations[0].Instances[0].PublicIpAddress' \
  --output text

2. SSH configを書けばVSCodeから1クリック接続

~/.ssh/configにホストを定義しておくと、VSCodeのコマンドパレットから「Remote-SSH: Connect to Host...」で接続先が選択肢に出てきます。

Host my-dev-server
  HostName 18.xxx.xxx.xxx
  User ec2-user
  IdentityFile ~/.ssh/my-ec2-key.pem

次回以降は左下の緑アイコン→ホスト名選択、だけで接続できます。ssh -i ~/.ssh/key.pem ec2-user@...を毎回打つ必要がなくなります。

3. EC2上でのGit設定とVSCodeのGUI操作

EC2側にGitを入れ、GitHub用のSSH鍵を生成します。

sudo yum install git -y
ssh-keygen -t ed25519 -C "your_email@example.com"
cat ~/.ssh/id_ed25519.pub  # GitHubのSSH keysに登録する

接続確認は以下で行います。

ssh -T git@github.com
# "Hi username! You've successfully authenticated..." と表示されればOK

ここから先はVSCodeの「ソース管理」パネルで完結します。ファイル横の「+」でステージング、コミットメッセージを入力して「✓」、「…」メニューからプッシュ。git add / git commit / git pushを手打ちする必要がありません。

4. ハマりやすいポイント:SG未開放でWebページが表示されない

セキュリティグループはデフォルトで全ポート閉じているため、Apache等を起動してもhttp://<EC2のIP>にアクセスできません。

# SGのIDを確認
aws ec2 describe-instances \
  --filters "Name=tag:Name,Values=MyDevServer" \
  --query 'Reservations[0].Instances[0].SecurityGroups[0].GroupId' \
  --output text

# ポート80を開放
aws ec2 authorize-security-group-ingress \
  --group-id sg-xxxxxxxxx \
  --protocol tcp \
  --port 80 \
  --cidr 0.0.0.0/0

検証用途なら0.0.0.0/0で構いませんが、本番運用では特定IPに絞ることを推奨します。

まとめ

AWS CLIでインフラをコード化し、VSCode Remote-SSHでEC2をローカル感覚で編集、Gitでバージョン管理する組み合わせは、コンソール操作に比べて再現性・効率とも大きく向上します。キーペア作成の前提から含めた全手順はこちらにまとめています。

VSCodeとAWS CLIで始めるAWS EC2環境構築(ブログ)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?