AWS CLIもしくはTerraformでSSM用のインスタンスプロファイルを作成する

# Instance Profile with AWS CLI

## Preperation

```bash
aws configure list
```

          Name                    Value             Type    Location
          ----                    -----             ----    --------
       profile                <not set>             None    None
    access_key     ****************GWVK shared-credentials-file    
    secret_key     ****************vWHJ shared-credentials-file    
        region                us-east-1      config-file    ~/.aws/config



```bash
ROLE_NAME="daisuke-test-role"
```


```bash
POLICY_NAME="AmazonSSMManagedInstanceCore"
POLICY_ARN="arn:aws:iam::aws:policy/${POLICY_NAME}"
```


```bash
PROFILE_NAME="daisuke-test-profile"
```

## Create IAM Role

### Create assume role policy


```bash
ASSUME_ROLE=$(cat << ETX
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "ec2.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
ETX)
echo $ASSUME_ROLE | jq .
```

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

### Create IAM Role (without IAM Policy)


```bash
aws iam create-role \
    --role-name ${ROLE_NAME} \
    --assume-role-policy-document "${ASSUME_ROLE}"
```

```json
{
    "Role": {
        "Path": "/",
        "RoleName": "daisuke-test-role",
        "RoleId": "AROAYEVEWBXL2PD2CT7UO",
        "Arn": "arn:aws:iam::777777777777:role/daisuke-test-role",
        "CreateDate": "2023-01-02T08:57:21+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "ec2.amazonaws.com"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        }
    }
}
```

### Check policy that will be atacched


```bash
aws iam get-policy --policy-arn ${POLICY_ARN}
```

```json
{
    "Policy": {
        "PolicyName": "AmazonSSMManagedInstanceCore",
        "PolicyId": "ANPAIXSHM2BNB2D3AXXRU",
        "Arn": "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
        "Path": "/",
        "DefaultVersionId": "v2",
        "AttachmentCount": 1,
        "PermissionsBoundaryUsageCount": 0,
        "IsAttachable": true,
        "Description": "The policy for Amazon EC2 Role to enable AWS Systems Manager service core functionality.",
        "CreateDate": "2019-03-15T17:22:12+00:00",
        "UpdateDate": "2019-05-23T16:54:21+00:00",
        "Tags": []
    }
}
```

### Attach IAM Policy to the Role


```bash
aws iam attach-role-policy \
  --role-name ${ROLE_NAME} \
  --policy-arn ${POLICY_ARN}
```


```bash
aws iam get-role --role-name ${ROLE_NAME}
```

```json
{
    "Role": {
        "Path": "/",
        "RoleName": "daisuke-test-role",
        "RoleId": "AROAYEVEWBXL2PD2CT7UO",
        "Arn": "arn:aws:iam::777777777777:role/daisuke-test-role",
        "CreateDate": "2023-01-02T08:57:21+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "ec2.amazonaws.com"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        },
        "MaxSessionDuration": 3600,
        "RoleLastUsed": {}
    }
}
```

### Check the atacched IAM policy


```bash
aws iam list-attached-role-policies --role-name ${ROLE_NAME}
```

```json
{
    "AttachedPolicies": [
        {
            "PolicyName": "AmazonSSMManagedInstanceCore",
            "PolicyArn": "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
        }
    ]
}
```


## Create Instance Profile

### Create Instance Profile


```bash
aws iam create-instance-profile --instance-profile-name ${PROFILE_NAME}
```

```json
{
    "InstanceProfile": {
        "Path": "/",
        "InstanceProfileName": "daisuke-test-profile",
        "InstanceProfileId": "AIPAYEVEWBXL5T4KHBMW2",
        "Arn": "arn:aws:iam::777777777777:instance-profile/daisuke-test-profile",
        "CreateDate": "2023-01-02T08:58:17+00:00",
        "Roles": []
    }
}
```

### Add IAM Role to Instance Profile


```bash
aws iam add-role-to-instance-profile \
    --instance-profile-name ${PROFILE_NAME} \
    --role-name ${ROLE_NAME}
```


```bash
aws iam get-instance-profile --instance-profile-name ${PROFILE_NAME}
```

```json
{
    "InstanceProfile": {
        "Path": "/",
        "InstanceProfileName": "daisuke-test-profile",
        "InstanceProfileId": "AIPAYEVEWBXL5T4KHBMW2",
        "Arn": "arn:aws:iam::777777777777:instance-profile/daisuke-test-profile",
        "CreateDate": "2023-01-02T08:58:17+00:00",
        "Roles": [
            {
                "Path": "/",
                "RoleName": "daisuke-test-role",
                "RoleId": "AROAYEVEWBXL2PD2CT7UO",
                "Arn": "arn:aws:iam::777777777777:role/daisuke-test-role",
                "CreateDate": "2023-01-02T08:57:21+00:00",
                "AssumeRolePolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {
                                "Service": "ec2.amazonaws.com"
                            },
                            "Action": "sts:AssumeRole"
                        }
                    ]
                }
            }
        ],
        "Tags": []
    }
}
```

## Clean UP


```bash
aws iam remove-role-from-instance-profile \
    --instance-profile-name ${PROFILE_NAME} \
    --role-name ${ROLE_NAME}
```


```bash
aws iam delete-instance-profile --instance-profile-name ${PROFILE_NAME}
```


```bash
aws iam detach-role-policy \
    --role-name ${ROLE_NAME} \
    --policy-arn ${POLICY_ARN}
```


```bash
aws iam delete-role --role-name ${ROLE_NAME}
```


# Instance Profile with terraform

## *.tfファイルの作成

```terraform:instance_profile.tf
# Role
resource "aws_iam_role" "dag_test_role" {
  name = "tf_daisuke_test_role" 
  assume_role_policy = file("./assume_role_policy.json")
}
 
# Role attachment
resource "aws_iam_role_policy_attachment" "dag_test_attach" {
  role       = aws_iam_role.dag_test_role.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}

# Instance Profile
resource "aws_iam_instance_profile" "dag_profile" {
  name  = "tf_daisuke_test_profile"
  role = aws_iam_role.dag_test_role.name
}
```

```terraform:output.tf
output "eip_for_ngw" {
  value = aws_iam_role.dag_test_role.arn
}

output "eip_for_slurm_compute_node" {
  value = aws_iam_instance_profile.dag_profile.arn
}
```

## terraformの実行

```bash
terraform init
```

```bash
terraform plan -out=./dryrun.log
```

```bash
terraform apply -auto-approve
```

## Ref

- https://docs.aws.amazon.com/ja_jp/systems-manager/latest/userguide/session-manager-prerequisites.html
- https://docs.aws.amazon.com/ja_jp/systems-manager/latest/userguide/setup-instance-profile.html
- https://docs.aws.amazon.com/cli/latest/reference/iam/index.html#cli-aws-iam
- https://aws.amazon.com/jp/premiumsupport/knowledge-center/attach-replace-ec2-instance-profile/
- https://zenn.dev/y_u_t_a/articles/58257348c3754d
- https://qiita.com/sakai00kou/items/a4b96dcfa6bb3e656cd9