Skip to content

AWS SSM経由でEC2にアクセスする

流れとしては、

text
Macブラウザ
  https://gitlab.pc2029nttd.com
  クライアント証明書を提示
    ↓ hostsで127.0.0.1へ
Mac localhost:443
    ↓ SSM port forwarding
GitLab EC2
    ↓ TCP転送先
ALB:443
    ↓ ALB mTLSで証明書検証
GitLab EC2:80

1. クライアント証明書インポート

省略

2. hosts書き換え

/etc/hosts

text
127.0.0.1	gitlab.pc2029nttd.com

を記載して、

bash
# 反映
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder

# 確認 -> 127.0.0.1が出ればOK
dscacheutil -q host -a name gitlab.pc2029nttd.com

3. SSMトンネルはる

bash
export AWS_REGION=ap-northeast-1
export GITLAB_INSTANCE_ID=i-0b582232a286a7569
export ALB_DNS=pc2029-alb-gitlab-1100306606.ap-northeast-1.elb.amazonaws.com
export AWS_BIN="$(command -v aws)"

sudo -E env HOME="$HOME" PATH="$PATH" AWS_REGION="$AWS_REGION" "$AWS_BIN" ssm start-session \
  --region "$AWS_REGION" \
  --target "$GITLAB_INSTANCE_ID" \
  --document-name AWS-StartPortForwardingSessionToRemoteHost \
  --parameters "{\"host\":[\"$ALB_DNS\"],\"portNumber\":[\"443\"],\"localPortNumber\":[\"443\"]}"

成功時:

bash
Port 443 opened ...
Waiting for connections...

4. ブラウザで開く

text
https://gitlab.pc2029nttd.com

【番外編】 git接続する

Gitにクライアント証明書を設定する

bash
mkdir -p ~/.certs/pc2029
chmod 700 ~/.certs/pc2029

openssl pkcs12 \
  -in /path/to/pc2029-gitlab-client-20260507.p12 \
  -clcerts -nokeys \
  -out ~/.certs/pc2029/gitlab-client.crt

openssl pkcs12 \
  -in /path/to/pc2029-gitlab-client-20260507.p12 \
  -nocerts -nodes \
  -out ~/.certs/pc2029/gitlab-client.key

chmod 600 ~/.certs/pc2029/gitlab-client.*

Git設定:

bash
git config --global http.https://gitlab.pc2029nttd.com.sslCert ~/.certs/pc2029/gitlab-client.crt
git config --global http.https://gitlab.pc2029nttd.com.sslKey ~/.certs/pc2029/gitlab-client.key
git config --global http.https://gitlab.pc2029nttd.com.sslCertType PEM
git config --global http.https://gitlab.pc2029nttd.com.sslKeyType PEM

確認:

bash
GIT_CURL_VERBOSE=1 git ls-remote https://gitlab.pc2029nttd.com/<group>/<project>.git