---
# System prepended metadata

title: 從 CLI 透過 SSM 登入 EC2 Instance
tags: [command, 'EC2 ', AWS, SSM, CLI]

---


[toc]

## Steps

### Credentials
> credential file 的產生需由 AWS Account 管理者操作和提供

例如 "MyDev.pem"，存放至路徑 `~/.ssh/`

### SSH Connection over Session Manager

開啟 SSH client config file

```shell
$ vim ~/.ssh/config 
```

編輯 SSH 連線參數設定，例：

```
# --- Some-instance-testing ---
Host Myweb-testing
    Hostname {instance-id}
    User ec2-user
    IdentityFile ~/.ssh/{credetial-file-name} 
    ProxyCommand sh -c "aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters 'portNumber=%p'"

```

### 以 SSH Connection 登入

完成之後，即可 CLI 登入 EC2 instance，例：

```
$ ssh Myweb-testing
```

## Tips

### AWS Systems Manager User Guide
- [Starting a session (SSH)](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html#sessions-start-ssh)
- [Allow and controlling permissions for SSH connections through Session Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started-enable-ssh-connections.html)

### 如何確認 EC2 Instance ID

#### Web Console

- 打開瀏覽器
- 登入 AWS Account web console
- 進入 EC2 管理介面查看 Instances 詳細資訊
- 找到欲登入的 EC2 Instance
- 點擊進去複製 Instance ID (都已經操作到這一步驟了，後續其實可以接著按 "Connect" 在 web console 進行作業就好了，只是你每次都得做這麼多動作)

#### AWS CLI 工具


Command Example: (一行指令解決)
```
$ aws ec2 describe-instances --filters 'Name=tag:Name,Values=Myweb-testing' | grep InstanceId
```
Result:
```
"InstanceId": "i-XXXXXXXXXX"
```

Tips for command-line:

- 列出全部的 EC2 Instances
```
$ aws ec2 describe-instances
```

- 以 Instance Type 篩選 EC2 Instances

```
$ aws ec2 describe-instances --filters 'Name=instance-type,Values=t3.small'
```

- 以名稱篩選 EC2 Instances
```
$ aws ec2 describe-instances --filters 'Name=tag:Name,Values=Some-instance-testing'
```
