Creating an IAM user and a S3 bucket using Python

Glody Mateta
3 min readDec 10, 2020

--

Hello World! In this short project we will learn how to manage AWS IAM users with python. Amazon Web Services (AWS) offers a service known as Identity and Access Management (IAM) that lets AWS Administrators provision and manage users and permissions in AWS cloud. AWS IAM can prove very useful for System Administrators looking to centrally manage users, permissions and credentials; in order to authorize user access on AWS services like EC2, S3, CloudWatch etc.

AWS SDK for Python, also known as the Boto3, makes user management very simple by letting developers and sysadmins write Python scripts to create and manage IAM users in AWS infrastructure. Before you can start writing Python programs to automate IAM, it is a prerequisite to configure AWS credentials in a Bash Shell environment. These credentials must have full admin rights to manage the AWS IAM service.

Creating a User and Assigning Policies

To create a new IAM user, you must first create an IAM client, then use the ‘create_user()’ method of the client object by passing a username to the name property ‘UserName’, as demonstrated in the following code sample.

import boto3

iam = boto3.client(‘iam’)

#create a user

iam.create_user( UserName=’Leveluppython’)

#attach a policy

iam.attach_user_policy(

UserName = ‘Leveluppython’,

PolicyArn=’arn:aws:iam::aws:policy/AmazonEC2FullAccess’

)

We will also assign a policy to set permissions on the new user object. In this case, I’ll grant the user full access on the EC2 service, but before we do that, we need to get the Policy ARN (Amazon Resource Number), which can be obtained from the AWS IAM console by searching for the required policy, as demonstrated in the screenshot below.

Once you have the Policy ARN and user created, simply use the ‘attach_user_policy()’ method of client object to pass the username and Policy ARN, which will attach the policy and permissions to the user object.

,

Log on to the AWS IAM Console to verify that the permissions are now set up for the new user by navigating to the Users>Name of User>Permissions tab.

The second part of the project we will create an Amazon S3 Bucket and upload a file in the bucket.

To create a S3 Bucket follow my code below, but replace the bucket name to your own unique name.

import boto3

s3 = boto3.client(‘s3’)

s3.create_bucket(Bucket=’bucketdev007')

To upload a file in a S3 bucket follow my code below.

import boto3

# Create an S3 client

s3 = boto3.client(‘s3’)

filename = ‘terrastate.jpeg’

bucket_name = ‘bucketdev007’

s3.upload_file(filename, bucket_name, filename)

In this project we learned how to create an IAM user and a S3 bucket. Have fun learning!!!!

--

--