Carlos Aguni

Highly motivated self-taught IT analyst. Always learning and ready to explore new skills. An eternal apprentice.


Boto3 IAM

04 Mar 2022 »

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/iam-example-policies.html

Create IAM Role

https://stackoverflow.com/questions/34188013/aws-create-role-has-prohibited-field

import json
import boto3

def lambda_handler(event, context):
    # TODO implement
    iam = boto3.client('iam')
    policy = {
      "Version": "2012-10-17",
      "Statement": {
        "Effect": "Allow",
        "Principal": {"Service": "lambda.amazonaws.com"},
        "Action": "sts:AssumeRole"
      }
    }
    rs = iam.create_role(
        RoleName='lambda-test-dlq',
        AssumeRolePolicyDocument=json.dumps(policy),
    )
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

Create IAM Policy

import json
import boto3

def lambda_handler(event, context):
    # TODO implement
    iam = boto3.client('iam')
    
    my_managed_policy = {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": "logs:CreateLogGroup",
                "Resource": "*"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "dynamodb:DeleteItem",
                    "dynamodb:GetItem",
                    "dynamodb:PutItem",
                    "dynamodb:Scan",
                    "dynamodb:UpdateItem"
                ],
                "Resource": "*"
            }
        ]
    }
    response = iam.create_policy(
      PolicyName='myDynamoDBPolicy',
      PolicyDocument=json.dumps(my_managed_policy)
    )
    print(response)
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

Get an IAM Policy

import boto3


# Create IAM client
iam = boto3.client('iam')

# Get a policy
response = iam.get_policy(
    PolicyArn='arn:aws:iam::aws:policy/AWSLambdaExecute'
)
print(response['Policy'])

Attach a managed role policy


import json
import boto3

def lambda_handler(event, context):
    # TODO implement
    iam = boto3.client('iam')
    
    iam.attach_role_policy(
        PolicyArn='arn:aws:iam::691262992979:policy/myDynamoDBPolicy',
        RoleName='lambda-test-dlq'
    )
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

Detach a managed policy

import boto3

# Create IAM client
iam = boto3.client('iam')

# Detach a role policy
iam.detach_role_policy(
    PolicyArn='arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess',
    RoleName='AmazonDynamoDBFullAccess'
)