LoginSignup
1
0

AWSEC2へのSSM経由SSH接続時のPermission denied (publickey)でハマった

Posted at

1. 概要

EC2に対してSSM経由でSSH接続したい場合は基本的にAWSのSSH 接続ガイドに従えばいいが
Permission denied (publickey)エラーでハマったので共有する。

2. 結論

以下の記事が参考になる.

結論から言えば今回の件の場合接続先のUser名を.ssh/configで指定する必要があった

UbuntuのEC2の場合User ubuntuと設定する必要がある。

3. 前提

3.1. 環境

  • 接続元: Windows11,AWSCLIは導入済
  • 接続先: UbuntuAMI,キーペア設定済
    上記のガイドに従いSSH接続のAWSのpolicyを割り当てる。
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ssm:StartSession",
            "Resource": [
                "arn:aws:ec2:region:account-id:instance/instance-id",
                "arn:aws:ssm:*:*:document/AWS-StartSSHSession"
            ],
            "Condition": {
                "BoolIfExists": {
                    "ssm:SessionDocumentAccessCheck": "true"
                }
             }
        }
    ]
}

次にSSH接続用の設定を行う。通常~/.ssh/configに存在する。(無い場合は作成する)
ガイドでは以下のように設定すればよいとされている。

# SSH over Session Manager
host i-* mi-*
    ProxyCommand C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters portNumber=%p"

4. 問題

秘密鍵の指定を適宜割り当てる。

# SSH over Session Manager
host i-* mi-*
    ProxyCommand C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters portNumber=%p"
    IdentityFile ~/.ssh/key.pem

こうすると以下のコマンドでSSH接続が可能になるが失敗する。

ssh i-fugafuga
hogehoge@i-fugafuga: Permission denied (publickey).

エラーの要因は秘密鍵の指定やタイポもあるがここでは接続先に存在するユーザに対応したユーザ名ではなかった事が原因となる。.ssh/configで未指定の場合はwindowsのユーザ名がログイン時に用いられる。
参考:https://stackoverflow.com/questions/18551556/permission-denied-publickey-when-ssh-access-to-amazon-ec2-instance

5. 解決策

UbuntuAMIの場合は以下のように.ssh/configを設定すればよい。

# SSH over Session Manager
host i-* mi-*
    ProxyCommand C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters portNumber=%p"
    IdentityFile ~/.ssh/key.pem
    User ubuntu
1
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
1
0