テストで使用するのでサクッと作りたいというご要望

方法

作成

bash
ROLE_NAME="szk302-iam-role"
aws iam create-role --role-name "${ROLE_NAME}" --assume-role-policy-document file://./ec2-assume-role-policy.json
ec2-assume-role-policy.json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "sts:AssumeRole"
            ],
            "Principal": {
                "Service": [
                    "ec2.amazonaws.com"
                ]
            }
        }
    ]
}

jsonファイル使わない版

bash
ROLE_NAME="szk302-iam-role"
aws iam create-role --role-name "${ROLE_NAME}" --assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["sts:AssumeRole"],"Principal":{"Service":["ec2.amazonaws.com"]}}]}'

ポリシーの付与

bash
ACCOUNT_ID="123456789101"
ROLE_NAME="szk302-iam-role"
POLICY_NAME="szk302-iam-policy"
POLICY_ARN="arn:aws:iam::${ACCOUNT_ID}:policy/${POLICY_NAME}"
aws iam attach-role-policy --policy-arn ${POLICY_ARN} --role-name "${ROLE_NAME}"

ポリシーの剥奪

bash
ACCOUNT_ID="123456789101"
ROLE_NAME="szk302-iam-role"
POLICY_NAME="szk302-iam-policy"
POLICY_ARN="arn:aws:iam::${ACCOUNT_ID}:policy/${POLICY_NAME}"
aws iam detach-role-policy --policy-arn ${POLICY_ARN} --role-name "${ROLE_NAME}"

削除

bash
ROLE_NAME="szk302-iam-role"
aws iam delete-role --role-name "${ROLE_NAME}"

備考

lambda版
ROLE_NAME="szk302-role"
aws iam create-role --role-name "${ROLE_NAME}" --assume-role-policy-document file://./lambda-assume-role-policy.json