Wednesday, May 28, 2025

IAM Part#3

 IAM Part#3

Class 33rd AWS IAM Roles May28th
Topics 
Working with Access keys.
IAM Roles
What is the AWS CLI?
How to download and install CLI?
IAM Operation with CLI
Working with CLI in Linux Machine
Working with CLI in AWS Cloud shell.

We able to access multiple way to access aws services ,so far we have used aws console only able connect using CLI ,Could shell,Programming(phython/java..etc)
 CLI Command line interface
 
   CLI Working with Access key 
Step1: For the ccitdev1 user ,i have disabled console access, trying to connect with Access key

>ccitdev1 >Security Credentials>Access key  >Click >Create access key

Give any name ,create access key
Download the key 

Practical : Using Access key and secret key Python program ,upload the file to s3 bucket

already i have s3 bucket ccitnewbucketcreated edit the permission tab give ACL enabled click save

And Uncheck Block public access click save changes


Phyton Script: 
Step1:
 Here boto3 is aws related framework for python program kit will available from boto3, we just
import boto3 (aws service we can access) using you acccess_key_id,secrete_access_key, previous which is you have download access key for the user ccitdev1, copy past the key

from flask import Flask, render_template, request, redirect, flash, url_for
import boto3
from botocore.exceptions import NoCredentialsError, PartialCredentialsError, ClientError
import os

app = Flask(__name__)
app.secret_key = 'your_secret_key'

# AWS S3 Configuration
S3_BUCKET = "ccitnewbucketcreated"
S3_REGION = "eu-west-1"

# Initialize S3 client
s3_client = boto3.client(
's3',
aws_access_key_id='your_access_key_id',
aws_secret_access_key='your_secret_access_key',
region_name=S3_REGION
)

# Check if the bucket exists, if not, create it
def create_bucket_if_not_exists():
try:
# Check if the bucket exists
s3_client.head_bucket(Bucket=S3_BUCKET)
except ClientError as e:
# If the bucket does not exist, create it
if e.response['Error']['Code'] == 'NoSuchBucket':
try:
s3_client.create_bucket(
Bucket=S3_BUCKET,
CreateBucketConfiguration={'LocationConstraint': S3_REGION}
)
flash(f"Bucket '{S3_BUCKET}' created successfully.")
except Exception as e:
flash(f"Error creating bucket: {e}")
else:
flash(f"Error accessing bucket: {e}")

# Home and File Upload Route
@app.route('/', methods=['GET', 'POST'])
def upload_file():
# Create the bucket if it doesn't exist
create_bucket_if_not_exists()

if request.method == 'POST':
if 'file' not in request.files:
flash('No file part in the request')
return redirect(request.url)

file = request.files['file']

if file.filename == '':
flash('No selected file')
return redirect(request.url)

try:
s3_client.upload_fileobj(
file,
S3_BUCKET,
file.filename
)
flash(f"File '{file.filename}' uploaded successfully to S3.")
return redirect(url_for('upload_file'))

except NoCredentialsError:
flash("Credentials not available.")
except PartialCredentialsError:
flash("Incomplete credentials provided.")
except Exception as e:
flash(f"Error uploading file: {e}")

# List files in the bucket to display them on the page
files = []
try:
response = s3_client.list_objects_v2(Bucket=S3_BUCKET)
if 'Contents' in response:
files = [file['Key'] for file in response['Contents']]
except Exception as e:
flash(f"Error retrieving files: {e}")

return render_template('upload.html', files=files)


# Route to delete a file from S3
@app.route('/delete/<filename>', methods=['POST'])
def delete_file(filename):
try:
s3_client.delete_object(Bucket=S3_BUCKET, Key=filename)
flash(f"File '{filename}' deleted successfully from S3.")
except Exception as e:
flash(f"Error deleting file: {e}")
return redirect(url_for('upload_file'))

if __name__ == '__main__':
app.run(debug=True)
Step2: Your local computer/laptop required python sotware/ and python charm 
After changes run the code in command prompt 
For boto3 installation 
pip install boto3
python.exe -m pip install --upgrade pip

Step3:
cmd>python app.py
 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 629-481-715

Upload any file ,uploaded successfully.


Object upload successfully using python program, using access key 

                                          Working with  CLI
Step1: Download software for windows and install , if you using amazon linux it will exist by default 
if windows need install manually 
https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html

Just for checking after installed CLI, if comes option installed successfully
PS C:\Users\Administrator> aws cli

usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:
Step2:Your credentials will store in below your user  directory 

C:\Users\Administrator\.aws
User : ccitdev1    
PS C:\Users\Administrator> aws configure
AWS Access Key ID [None]: AKIATFBMO7H4N2HZHWK4
AWS Secret Access Key [None]: AA+u55BJzgDBIgci5RGL7eZOi0DSAxL/G2EUuOLH
Default region name [None]: eu-west-1
Default output format [None]:

Step3:copy one file to s3 bucket uploaded successfully
PS C:\Users\Administrator> aws s3 cp "C:\Users\Administrator\Desktop\Pht\5.png" "s3://ccitnewbucketcreated"
upload: Desktop\Pht\5.png to s3://ccitnewbucketcreated/5.png


Download the files from aws bucket
PS C:\Users\Administrator> aws s3 cp  "s3://ccitnewbucketcreated/5.png" "C:\Users\Administrator\Desktop\Pht"
download: s3://ccitnewbucketcreated/5.png to Desktop\Pht\5.png


                                                               IAM Role 
Aws Role( role simply ,we attach the role to service, not for the iam user)

1.       A role is a set of permission that grant access to actions and resources in AWS. These permissions are attached to the role,not to an IAM user or a group.

2.       An IAM user can use a role in the same AWS account or a different account.

3.       An IAM user is similar to an IAM user, role is also an AWS identity with permission policies that determine what the identity can and cannot do in aws.

4.       A role is not uniquely associated with a single person,it can be used by anyone who needs it.

5.       You can use the roles to delegate access to users,applications or services that generally do not have access to you aws resources 

For example : communicate one service to other service ,S3 data move to rds using lambda
communicate service we need permission, the permission we will give from role

S3-->lambda -->Rds 
Step1: Create one Instance Windows 
Aws Service (Ec2,S3,lambda..etc)
Aws account (we give permission to other account also)

Select service Ec2  click next

Give permission to S3 access for Ec2 service

Click next 
Give any name for the role Ec2-S3-Role,Click Create role , see below json script understand, giving permission to ec2 service


Step2:Create one windows instances and generated the password. Security >Get windows password upload you .pem file which you have added window key while creating instance.
Instance ID
i-0cdeaff2968b40266
Private IP address
10.0.2.107
Username
Administrator
Password
YDQE3ooRAdDac?hFShM.qZmC5FmerGti

After launch windows remotely using public ip and mstsc, download the window CLI software in  you remote desktop and install, After installation completed.


Step3: Now we need give Role base authentication to our instance
Select the instance >security >Modify IAM role ,assign role which you have create and update IAM role
Step4:
Remote machine successfully uploaded the file using IAM role based 
C:\Users\Administrator\Desktop\images>aws s3 cp "./Image1.png" "s3://ccitnewbucketcreated/"
upload: .\Image1.png to s3://ccitnewbucketcreated/Image1.png
  
Step5:

Step6: Now this code those two lines not required , it will come to Role based with out accesskey and secrete key.

Amazon Linux CLI in built in exist you just configure the key.


CLI Using create user existing user add permision IAM full access 

Step1:

Step2:I have executed this in cmd prompt 

PS C:\Users\Administrator> aws iam create-user --user-name ccitvdev2
{
    "User": {
        "Path": "/",
        "UserName": "ccitvdev2",
        "UserId": "AIDATFBMO7H4DAX5TNEKR",
        "Arn": "arn:aws:iam::216989104632:user/ccitvdev2",
        "CreateDate": "2025-06-03T13:09:36+00:00"
    }
}
Step3:
Step4:
PS C:\Users\Administrator> aws iam delete-user --user-name ccitvdev2
PS C:\Users\Administrator>


Working with CLI in AWS Cloud shell.
AWS CloudShell is a browser-based shell provided by Amazon web services(AWS) that allow you to manage you AWS resources directly from the AWS Management console,without needing to install or configure anything locally.

Step1:

We have inbuilt in service is cloud shell it is work just like linux CLI ,with not EC2 linux instance.
it has inbuilt git,python,java along with 1 GB storage also available 


You need permission for the user 
~ $ git --version
git version 2.47.1
~ $ python --version
Python 3.9.21
~ $ java --version
openjdk 21.0.7 2025-04-15 LTS
OpenJDK Runtime Environment Corretto-21.0.7.6.1 (build 21.0.7+6-LTS)
OpenJDK 64-Bit Server VM Corretto-21.0.7.6.1 (build 21.0.7+6-LTS, mixed mode, sharing)
~ $ aws s3 ls
2025-05-31 03:58:25 ccitbuckets3bucket
2025-06-01 16:39:14 ccitdev1june
2025-06-01 14:43:56 ccitnewbucketcreated
~ $ aws iam create-user --user-name ccitdev3
{
    "User": {
        "Path": "/",
        "UserName": "ccitdev3",
        "UserId": "AIDATFBMO7H4NYV4JMAIR",
        "Arn": "arn:aws:iam::216989104632:user/ccitdev3",
        "CreateDate": "2025-06-03T13:30:02+00:00"
    }
}



if you want to test any python code you can test simple code .
Cloud shell is free tier, using Cloud shell create resource will be chargeable

Maximum one AWS account 5000 user we will create. 

--Thanks








No comments:

Post a Comment