IAM User Practice

Page content

라이브러리 불러오기

  • 기 설치된 라이브러리를 불러오도록 한다.
import boto3
print(boto3.__version__)
1.23.5

IAM User 관련 주요 코드

  • 다음 코드는 유저를 생성하는 코드이다.
def create_user(username):
    iam = boto3.client('iam')
    response = iam.create_user(UserName=username)
    print(response)

create_user('testuser2fromwsl2')
{'User': {'Path': '/', 'UserName': 'testuser2fromwsl2', 'UserId': 'AIDAVRRRQ3HFXFQPOOY7Q', 'Arn': 'arn:aws:iam::381282212299:user/testuser2fromwsl2', 'CreateDate': datetime.datetime(2022, 5, 24, 5, 30, 6, tzinfo=tzutc())}, 'ResponseMetadata': {'RequestId': 'd5fa242b-9aa9-4ad9-a75a-ed23e041d4ba', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'd5fa242b-9aa9-4ad9-a75a-ed23e041d4ba', 'content-type': 'text/xml', 'content-length': '495', 'date': 'Tue, 24 May 2022 05:30:05 GMT'}, 'RetryAttempts': 0}}
  • 이번에는 모든 사용자를 가져오는 코드를 작성한다.
def all_users():
    iam = boto3.client('iam')
    paginator = iam.get_paginator('list_users')
    for response in paginator.paginate():
        for user in response['Users']:
            username = user['UserName']
            Arn = user['Arn']
            print('Username : {} Arn : {}'.format(username, Arn))

all_users()
Username : aws-wsl2 Arn : arn:aws:iam::381282212299:user/aws-wsl2
Username : human Arn : arn:aws:iam::381282212299:user/human
Username : human-m1 Arn : arn:aws:iam::381282212299:user/human-m1
Username : testuser Arn : arn:aws:iam::381282212299:user/testuser
Username : testuser2 Arn : arn:aws:iam::381282212299:user/testuser2
Username : testuser2fromwsl2 Arn : arn:aws:iam::381282212299:user/testuser2fromwsl2
Username : testuser3 Arn : arn:aws:iam::381282212299:user/testuser3
  • 이번에는 사용자 이름을 변경한다.
    • testuser2fromwsl2 이름을 updatetest로 변경하는 코드다.
def update_user(old_username, new_username):
    iam = boto3.client('iam')
    
    response = iam.update_user(
        UserName=old_username, 
        NewUserName=new_username
    )
    
    print(response)

update_user('testuser2fromwsl2', 'updatetest')
all_users()
{'ResponseMetadata': {'RequestId': '4a567c96-d5ce-4e76-9344-6ab762fc9e01', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '4a567c96-d5ce-4e76-9344-6ab762fc9e01', 'content-type': 'text/xml', 'content-length': '200', 'date': 'Tue, 24 May 2022 05:30:16 GMT'}, 'RetryAttempts': 0}}
Username : aws-wsl2 Arn : arn:aws:iam::381282212299:user/aws-wsl2
Username : human Arn : arn:aws:iam::381282212299:user/human
Username : human-m1 Arn : arn:aws:iam::381282212299:user/human-m1
Username : testuser Arn : arn:aws:iam::381282212299:user/testuser
Username : testuser2 Arn : arn:aws:iam::381282212299:user/testuser2
Username : testuser3 Arn : arn:aws:iam::381282212299:user/testuser3
Username : updatetest Arn : arn:aws:iam::381282212299:user/updatetest

Python AWS 연동 예제

import boto3
import json

def create_policy():
    iam = boto3.client('iam')

    user_policy = {
        "Version":"2012-10-17",
        "Statement":[
            {
                "Effect": "Allow",
                "Action": "*",
                "Resource": "*"
            }
        ]
    }

    response = iam.create_policy(
        PolicyName = 'pyFullAccess',
        PolicyDocument=json.dumps(user_policy)
    )
    print(response)


create_policy()
{'Policy': {'PolicyName': 'pyFullAccess', 'PolicyId': 'ANPAVRRRQ3HFQIRVWB2MX', 'Arn': 'arn:aws:iam::381282212299:policy/pyFullAccess', 'Path': '/', 'DefaultVersionId': 'v1', 'AttachmentCount': 0, 'PermissionsBoundaryUsageCount': 0, 'IsAttachable': True, 'CreateDate': datetime.datetime(2022, 5, 23, 5, 40, 21, tzinfo=tzutc()), 'UpdateDate': datetime.datetime(2022, 5, 23, 5, 40, 21, tzinfo=tzutc())}, 'ResponseMetadata': {'RequestId': '8da83bae-6c24-4104-9da4-22795e46652a', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '8da83bae-6c24-4104-9da4-22795e46652a', 'content-type': 'text/xml', 'content-length': '759', 'date': 'Mon, 23 May 2022 05:40:21 GMT'}, 'RetryAttempts': 0}}
  • AWS 콘솔창에서 IAM 대시보드에서 정책을 클릭하면 PolicyName인 pyFullAccess가 등록되어 있는 것을 확인할 수 있다.

  • 이번에는 모든 AWS IAM 정책을 출력하도록 한다.
def list_policies():
    iam = boto3.client('iam')

    paginator = iam.get_paginator('list_policies')

    for response in paginator.paginate(Scope="AWS"):
        for policy in response['Policies']:
            policy_name = policy['PolicyName']
            Arn = policy['Arn']

            print('Policy Name : {} Arn : {}'.format(policy_name, Arn))

list_policies()
Policy Name : AWSDirectConnectReadOnlyAccess Arn : arn:aws:iam::aws:policy/AWSDirectConnectReadOnlyAccess
Policy Name : AmazonGlacierReadOnlyAccess Arn : arn:aws:iam::aws:policy/AmazonGlacierReadOnlyAccess
...
Policy Name : AmazonRedshiftDataFullAccess Arn : arn:aws:iam::aws:policy/AmazonRedshiftDataFullAccess
Policy Name : AWSApplicationMigrationReplicationServerPolicy Arn : arn:aws:iam::aws:policy/service-role/AWSApplicationMigrationReplicationServerPolicy
  • 이번에는 Policy를 Python을 활용하여 사용자에 추가하도록 한다.
    • PolicyArn을 획득하는 방법은 아래 그림처럼 획득하면 된다.
def attach_policy(policy_arn, username):
    iam = boto3.client('iam')
    response = iam.attach_user_policy(
        UserName=username,
        PolicyArn=policy_arn
    )
    print(response)

attach_policy('arn:aws:iam::aws:policy/AmazonRDSFullAccess', 'testuser')
{'ResponseMetadata': {'RequestId': '0e518ab3-48e6-4b43-9e58-b14643445dbb', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '0e518ab3-48e6-4b43-9e58-b14643445dbb', 'content-type': 'text/xml', 'content-length': '212', 'date': 'Mon, 23 May 2022 06:20:03 GMT'}, 'RetryAttempts': 0}}
  • 실제로 적용이 되었는지, ’testuser’ 사용자 계정에서 직접 확인해보자.

  • 정책을 추가했다면, 반대로 삭제도 가능하다.

    • 실제 User에 해당 Policy가 있는지 확인 후 코드를 작성한다.
iam = boto3.client('iam')
response = iam.detach_user_policy(
    UserName='updatetest',
    PolicyArn = 'arn:aws:iam::381282212299:policy/pyFullAccess'
)

print(response)
{'ResponseMetadata': {'RequestId': 'd6ed8035-4cb3-41f5-9d2c-adcf49633441', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'd6ed8035-4cb3-41f5-9d2c-adcf49633441', 'content-type': 'text/xml', 'content-length': '212', 'date': 'Mon, 23 May 2022 07:02:10 GMT'}, 'RetryAttempts': 0}}
  • IAM User Group을 생성한다.
def create_group(group_name):
    iam = boto3.client('iam')
    iam.create_group(GroupName=group_name)

create_group('S3Admins')
  • 그룹을 생성했다 하더라도, 정책을 추가한 것은 아니다. 따라서, 해당 정책을 추가할 것이다.
def attach_policy(policy_arn, group_name):
    iam = boto3.client('iam')
    response = iam.attach_group_policy(
        GroupName=group_name,
        PolicyArn=policy_arn
    )

    print(response)

attach_policy('arn:aws:iam::aws:policy/AmazonS3FullAccess','S3Admins')
{'ResponseMetadata': {'RequestId': 'd45aa4fa-3851-4b86-93aa-a8077dc45563', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'd45aa4fa-3851-4b86-93aa-a8077dc45563', 'content-type': 'text/xml', 'content-length': '214', 'date': 'Mon, 23 May 2022 07:33:56 GMT'}, 'RetryAttempts': 0}}
  • 생성 후, 사용자 그룹에서 그룹 이름을 클릭하고, 권한 탭을 누르면 방금 추가한 정책을 확인할 수 있다.

  • 이번에는 사용자를 IAM User Group에 추가하는 코드를 작성한다.
    • 기존 사용자 중 임의의 사용자를 추가한다.
all_users()
Username : aws-wsl2 Arn : arn:aws:iam::381282212299:user/aws-wsl2
Username : human Arn : arn:aws:iam::381282212299:user/human
Username : human-m1 Arn : arn:aws:iam::381282212299:user/human-m1
Username : testuser Arn : arn:aws:iam::381282212299:user/testuser
Username : testuser2 Arn : arn:aws:iam::381282212299:user/testuser2
Username : testuser3 Arn : arn:aws:iam::381282212299:user/testuser3
Username : updatetest Arn : arn:aws:iam::381282212299:user/updatetest
def add_user(username, group_name):
    iam = boto3.client('iam')

    response = iam.add_user_to_group(
        UserName=username,
        GroupName=group_name
    )

    print(response)

add_user('testuser3', 'S3Admins')
{'ResponseMetadata': {'RequestId': '2d7f9c09-3821-42b3-aad3-14598eab5ab4', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '2d7f9c09-3821-42b3-aad3-14598eab5ab4', 'content-type': 'text/xml', 'content-length': '208', 'date': 'Mon, 23 May 2022 07:26:05 GMT'}, 'RetryAttempts': 0}}
  • 실제 이 그룹의 사용자 이름이 추가가 되었는지 확인할 수 있다.

  • 이번에는 User Group에서 Policy를 제거하도록 한다.
    • 함수 실행 전, 실제 Policy가 등록이 되어 있는지 확인한다.
def detach_group(user_group, arn):
    iam = boto3.client('iam')

    response = iam.detach_group_policy(
        GroupName=user_group,
        PolicyArn = arn
    )

    print(response)

detach_group('S3Admins', 'arn:aws:iam::aws:policy/AmazonS3FullAccess')
{'ResponseMetadata': {'RequestId': '396fa337-078b-4ca3-8791-24dca7913b9f', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '396fa337-078b-4ca3-8791-24dca7913b9f', 'content-type': 'text/xml', 'content-length': '214', 'date': 'Mon, 23 May 2022 07:34:03 GMT'}, 'RetryAttempts': 0}}
  • 이번에는 사용자를 위한 Create Access Key를 생성한다.
all_users()
Username : aws-wsl2 Arn : arn:aws:iam::381282212299:user/aws-wsl2
Username : human Arn : arn:aws:iam::381282212299:user/human
Username : human-m1 Arn : arn:aws:iam::381282212299:user/human-m1
Username : testuser Arn : arn:aws:iam::381282212299:user/testuser
Username : testuser2 Arn : arn:aws:iam::381282212299:user/testuser2
Username : testuser3 Arn : arn:aws:iam::381282212299:user/testuser3
Username : updatetest Arn : arn:aws:iam::381282212299:user/updatetest
def create_access(username):
    iam = boto3.client('iam')

    response = iam.create_access_key(
        UserName=username
    )
    
    print(response)

create_access('testuser2')
{'AccessKey': {'UserName': 'testuser2', 'AccessKeyId': 'AKIAVRRRQ3HFVT4XJEXH', 'Status': 'Active', 'SecretAccessKey': '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', 'CreateDate': datetime.datetime(2022, 5, 23, 7, 36, 10, tzinfo=tzutc())}, 'ResponseMetadata': {'RequestId': '2e0400a4-6ae0-494c-b131-37b7a9b65bb7', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '2e0400a4-6ae0-494c-b131-37b7a9b65bb7', 'content-type': 'text/xml', 'content-length': '601', 'date': 'Mon, 23 May 2022 07:36:10 GMT'}, 'RetryAttempts': 0}}
  • 이번에는 Access 키를 제한한다.
def update_access():
    iam = boto3.client('iam')
    iam.update_access_key(
        AccessKeyId = 'AKIAVRRRQ3HFVT4XJEXH', 
        Status = 'Inactive', 
        UserName = 'testuser2'
    )
    
update_access()
  • 위 코드를 실행하면 비활성화로 전환되는 것을 확인할 수 있다.

  • 위 코드를 실행하면 비활성화로 전환되는 것을 확인할 수 있다.

  • 이제 사용자를 제거해본다.

all_users()
Username : aws-wsl2 Arn : arn:aws:iam::381282212299:user/aws-wsl2
Username : human Arn : arn:aws:iam::381282212299:user/human
Username : human-m1 Arn : arn:aws:iam::381282212299:user/human-m1
Username : testuser Arn : arn:aws:iam::381282212299:user/testuser
Username : testuser2 Arn : arn:aws:iam::381282212299:user/testuser2
Username : testuser3 Arn : arn:aws:iam::381282212299:user/testuser3
Username : updatetest Arn : arn:aws:iam::381282212299:user/updatetest
def delete_myuser(username):
    iam = boto3.client('iam')

    response = iam.delete_user(
        UserName=username
    )

    print(response)

delete_myuser('updatetest')
{'ResponseMetadata': {'RequestId': 'fb179cd6-568b-4380-b094-8a02109a9682', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'fb179cd6-568b-4380-b094-8a02109a9682', 'content-type': 'text/xml', 'content-length': '200', 'date': 'Mon, 23 May 2022 08:21:43 GMT'}, 'RetryAttempts': 0}}
all_users()
Username : aws-wsl2 Arn : arn:aws:iam::381282212299:user/aws-wsl2
Username : human Arn : arn:aws:iam::381282212299:user/human
Username : human-m1 Arn : arn:aws:iam::381282212299:user/human-m1
Username : testuser Arn : arn:aws:iam::381282212299:user/testuser
Username : testuser2 Arn : arn:aws:iam::381282212299:user/testuser2
Username : testuser3 Arn : arn:aws:iam::381282212299:user/testuser3
all_users()
Username : aws-wsl2 Arn : arn:aws:iam::381282212299:user/aws-wsl2
Username : human Arn : arn:aws:iam::381282212299:user/human
Username : human-m1 Arn : arn:aws:iam::381282212299:user/human-m1
Username : testuser Arn : arn:aws:iam::381282212299:user/testuser
Username : testuser2 Arn : arn:aws:iam::381282212299:user/testuser2
Username : testuser3 Arn : arn:aws:iam::381282212299:user/testuser3
Username : updatetest Arn : arn:aws:iam::381282212299:user/updatetest
def delete_user_group(username, groupName):
    iam = boto3.resource('iam')

    group = iam.Group(groupName)

    response = group.remove_user(
        UserName=username
    )

    print(response)

delete_user_group('testuser3', 'S3Admins')
{'ResponseMetadata': {'RequestId': '643c6a31-eb8e-4736-8c6d-363b490cb464', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '643c6a31-eb8e-4736-8c6d-363b490cb464', 'content-type': 'text/xml', 'content-length': '218', 'date': 'Tue, 24 May 2022 05:30:37 GMT'}, 'RetryAttempts': 0}}