3. Create IAM Role and Policy

In this step, we will create an AWS IAM role and associate a resource policy to it to give our AWS Lambda function the right amount of permissions to describe and act on the instances created in Step 2 and send a notification through the SNS topic created in Step 1.

  1. Navigate to the AWS IAM console by clicking on the Find Services search bar, typing IAM in the search bar, and pressing Enter.

    Open IAM console

  2. Click on Roles

  3. Click on Create Role

  4. Leave AWS service as the trusted entity.

  5. Under Choose the service that will use this role click on Lambda

  6. Click on Next: Permissions

  7. Click on Create policy, a new page will open up

  8. Click on the JSON tab

  9. In the editing area, paste the below policy:

Be sure to replace <<ARN_of_SNS_Topic>> with the topic ARN you created as part of Step 1.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*",
            "Effect": "Allow",
            "Sid": "AllowLambdaPermissionsToLogInCloudWatchLogs"
        },
        {
            "Action": [
                "sns:Publish"
            ],
            "Resource": "<<ARN_of_SNS_TOPIC>>",
            "Effect": "Allow",
            "Sid": "AllowLambdaPermissionsToPublishSNS"
        },
        {
            "Action": [
                "ec2:DescribeInstances",
                   "ec2:TerminateInstances",
                   "ec2:StopInstances"
            ],
            "Resource": "*",
            "Effect": "Allow",
            "Sid": "AllowLambdaPermissionsToDescribeStopTerminateEC2"
        }
    ]
}
  1. Click on Review policy

  2. Give the policy a name and an optional description. Example: aws_health_dos_lambda_policy

  3. Click on Create policy

  4. Close the new page and go back to the Create role page.

The next steps refer to the initial page were we initiated the policy creation. Ensure the new page has been closed and that you are working on the page you navigated to in step 1.

  1. Click on the refresh button to reload the available poicies.

    Refresh policies

  2. Select the policy you created in step 3.12

  3. Click on Next: Tags

  4. Click on Next: Review

  5. In the Role name text box, type aws_health_dos_lambda_role_reinvent

  6. Click Create role