AWS Cloud9環境のCloudShellでの構築

:::note info
目的
- AWS on for beginnersのハンズオンをCLIで実施するためのCloud9環境を用意する
- VPCとサブネットはデフォルトで作成されているものを使用
- EC2への接続方法はSSMを使用
:::

構成図
![cloud9.drawio.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3297641/5c890fdc-0257-fae9-62f3-1394c514be61.png)
# 構築
## IAMロール作成
※作成済みの場合は不要
```bash:コマンド
aws iam create-role --role-name AWSCloud9SSMAccessRole --path /service-role/ --assume-role-policy-document '{"Version": "2012-10-17","Statement": [{"Effect": "Allow","Principal": {"Service": ["ec2.amazonaws.com","cloud9.amazonaws.com"]      },"Action": "sts:AssumeRole"}]}'
aws iam attach-role-policy --role-name AWSCloud9SSMAccessRole --policy-arn arn:aws:iam::aws:policy/AWSCloud9SSMInstanceProfile
aws iam create-instance-profile --instance-profile-name AWSCloud9SSMInstanceProfile --path /cloud9/
aws iam add-role-to-instance-profile --instance-profile-name AWSCloud9SSMInstanceProfile --role-name AWSCloud9SSMAccessRole
```
```bash:出力
[cloudshell-user@ip-10-134-6-238 ~]$ aws iam create-role --role-name AWSCloud9SSMAccessRole --path /service-role/ --assume-role-policy-document '{"Version": "2012-10-17","Statement": [{"Effect": "Allow","Principal": {"Service": ["ec2.amazonaws.com","cloud9.amazonaws.com"]      },"Action": "sts:AssumeRole"}]}'
{
    "Role": {
        "Path": "/service-role/",
        "RoleName": "AWSCloud9SSMAccessRole",
        "RoleId": "AROA4MTWMHGDBT5RJEQKI",
        "Arn": "arn:aws:iam::999999999999:role/service-role/AWSCloud9SSMAccessRole",
        "CreateDate": "2024-02-08T04:09:25+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "Service": [
                            "ec2.amazonaws.com",
                            "cloud9.amazonaws.com"
                        ]
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        }
    }
}
[cloudshell-user@ip-10-134-6-238 ~]$ aws iam attach-role-policy --role-name AWSCloud9SSMAccessRole --policy-arn arn:aws:iam::aws:policy/AWSCloud9SSMInstanceProfile
[cloudshell-user@ip-10-134-6-238 ~]$ aws iam create-instance-profile --instance-profile-name AWSCloud9SSMInstanceProfile --path /cloud9/
{
    "InstanceProfile": {
        "Path": "/cloud9/",
        "InstanceProfileName": "AWSCloud9SSMInstanceProfile",
        "InstanceProfileId": "AIPA4MTWMHGDH22ATE7JI",
        "Arn": "arn:aws:iam::999999999999:instance-profile/cloud9/AWSCloud9SSMInstanceProfile",
        "CreateDate": "2024-02-08T04:09:29+00:00",
        "Roles": []
    }
}
[cloudshell-user@ip-10-134-6-238 ~]$ aws iam add-role-to-instance-profile --instance-profile-name AWSCloud9SSMInstanceProfile --role-name AWSCloud9SSMAccessRole
[cloudshell-user@ip-10-134-6-238 ~]$
```
## (変数設定)VPC ID
```bash:コマンド
EC2_VPC_ID=$( \
  aws ec2 describe-vpcs \
    --region ap-northeast-1 \
    --filters Name=is-default,Values=true \
    --query 'Vpcs[].VpcId' \
    --output text
) \
&& echo ${EC2_VPC_ID}
```
```bash:出力
[cloudshell-user@ip-10-134-6-238 ~]$ EC2_VPC_ID=$( \
>   aws ec2 describe-vpcs \
>     --region ap-northeast-1 \
>     --filters Name=is-default,Values=true \
>     --query 'Vpcs[].VpcId' \
>     --output text
> ) \
> && echo ${EC2_VPC_ID}
vpc-0a7c28cd53ed28d0e
```
## (変数設定)サブネット ID
```bash:コマンド
EC2_SUBNET_ID=$( \
  aws ec2 describe-subnets \
    --region ap-northeast-1 \
    --filters Name=vpc-id,Values=${EC2_VPC_ID} \
              Name=availability-zone,Values="ap-northeast-1c" \
    --query "Subnets[].SubnetId" \
    --output text \
) \
&& echo ${EC2_SUBNET_ID}
```
```bash:出力
[cloudshell-user@ip-10-134-6-238 ~]$ EC2_SUBNET_ID=$( \
>   aws ec2 describe-subnets \
>     --region ap-northeast-1 \
>     --filters Name=vpc-id,Values=${EC2_VPC_ID} \
>               Name=availability-zone,Values="ap-northeast-1c" \
>     --query "Subnets[].SubnetId" \
>     --output text \
> ) \
> && echo ${EC2_SUBNET_ID}
subnet-03adbc40c8dd6b604
```
## EC2 環境作成
※instance-typeは無料利用枠がある場合はt2.micro、無料利用枠がない場合はt3.microを使用
```bash:コマンド
aws cloud9 create-environment-ec2 \
  --name hands-on-for-beginners \
  --description "AWS Hands-on for Beginners" \
  --instance-type t2.micro \
  --image-id resolve:ssm:/aws/service/cloud9/amis/amazonlinux-2023-x86_64 \
  --region ap-northeast-1 \
  --connection-type CONNECT_SSM \
  --subnet-id ${EC2_SUBNET_ID} \
  --automatic-stop-time-minutes 30
```
```bash:出力
[cloudshell-user@ip-10-134-6-238 ~]$ aws cloud9 create-environment-ec2 \
>   --name hands-on-for-beginners \
>   --description "AWS Hands-on for Beginners" \
>   --instance-type t2.micro \
>   --image-id resolve:ssm:/aws/service/cloud9/amis/amazonlinux-2023-x86_64 \
>   --region ap-northeast-1 \
>   --connection-type CONNECT_SSM \
>   --subnet-id ${EC2_SUBNET_ID} \
>   --automatic-stop-time-minutes 30
{
    "environmentId": "285828429dc343278de3d3455ec1ac67"
}
```
## (変数設定)環境ID
```bash:コマンド
ENVIRONMENTID=$( \
  aws cloud9 list-environments \
    --region ap-northeast-1 \
    --query environmentIds \
    --output text \
) \
&& echo ${ENVIRONMENTID}
```
```bash:出力
[cloudshell-user@ip-10-134-6-238 ~]$ ENVIRONMENTID=$( \
>   aws cloud9 list-environments \
>     --region ap-northeast-1 \
>     --query environmentIds \
>     --output text \
> ) \
> && echo ${ENVIRONMENTID}
285828429dc343278de3d3455ec1ac67
```
## (確認)ステータス情報取得
```bash:コマンド
aws cloud9 describe-environment-status \
  --environment-id ${ENVIRONMENTID} \
  --region ap-northeast-1
```
```bash:出力
[cloudshell-user@ip-10-134-6-238 ~]$ aws cloud9 describe-environment-status \
>   --environment-id ${ENVIRONMENTID} \
>   --region ap-northeast-1
{
    "status": "ready",
    "message": "Environment is ready to use."
}
```
## (確認)環境情報
```bash:コマンド
aws cloud9 describe-environments \
  --environment-ids ${ENVIRONMENTID} \
  --region ap-northeast-1
```
```bash:出力
[cloudshell-user@ip-10-134-6-238 ~]$ aws cloud9 describe-environments \
>   --environment-ids ${ENVIRONMENTID} \
>   --region ap-northeast-1
{
    "environments": [
        {
            "id": "285828429dc343278de3d3455ec1ac67",
            "name": "hands-on-for-beginners",
            "description": "AWS Hands-on for Beginners",
            "type": "ec2",
            "connectionType": "CONNECT_SSM",
            "arn": "arn:aws:cloud9:ap-northeast-1:999999999999:environment:285828429dc343278de3d3455ec1ac67",
            "ownerArn": "arn:aws:sts::999999999999:assumed-role/AWSReservedSSO_Cloud9_61ef1983d2a51f0e/handson-user",
            "lifecycle": {
                "status": "CREATED"
            },
            "managedCredentialsStatus": "DISABLED_BY_DEFAULT"
        }
    ]
}
```
# 削除
## EC2 環境削除
```bash:コマンド
aws cloud9 delete-environment --environment-id ${ENVIRONMENTID}
```
```bash:出力
[cloudshell-user@ip-10-132-72-116 ~]$ aws cloud9 delete-environment --environment-id ${ENVIRONMENTID}
[cloudshell-user@ip-10-132-72-116 ~]$
```
## IAMロール削除
```bash:コマンド
aws iam remove-role-from-instance-profile --instance-profile-name AWSCloud9SSMInstanceProfile --role-name AWSCloud9SSMAccessRole
aws iam delete-instance-profile --instance-profile-name AWSCloud9SSMInstanceProfile
aws iam detach-role-policy --role-name AWSCloud9SSMAccessRole --policy-arn arn:aws:iam::aws:policy/AWSCloud9SSMInstanceProfile
aws iam delete-role --role-name AWSCloud9SSMAccessRole```
```
```bash:出力
[cloudshell-user@ip-10-134-6-238 ~]$ aws iam remove-role-from-instance-profile --instance-profile-name AWSCloud9SSMInstanceProfile --role-name AWSCloud9SSMAccessRole
[cloudshell-user@ip-10-134-6-238 ~]$ aws iam delete-instance-profile --instance-profile-name AWSCloud9SSMInstanceProfile
[cloudshell-user@ip-10-134-6-238 ~]$ aws iam detach-role-policy --role-name AWSCloud9SSMAccessRole --policy-arn arn:aws:iam::aws:policy/AWSCloud9SSMInstanceProfile
[cloudshell-user@ip-10-134-6-238 ~]$ aws iam delete-role --role-name AWSCloud9SSMAccessRole
```

# 参考

https://docs.aws.amazon.com/ja_jp/cloud9/latest/user-guide/tutorial-basic-cli.html

https://jawsug-cli.connpass.com/