Bỏ qua

file này đọc vui thôi bạn nên xem video hoặc tự configure qua aws study group đây có hướng dẫn lab https://000001.awsstudygroup.com/

🚀 AWS Fundamentals: Complete Guide to Account Setup, Security, and IAM Management

Published on August 8, 2025 | By lelongc


📖 Table of Contents

  1. Introduction
  2. STEP 1: Creating Your General AWS Account
  3. Understanding Multi-Factor Authentication (MFA)
  4. STEP 2: Securing Your General AWS Account
  5. STEP 3: Creating a Budget for Cost Control
  6. DIY Challenge: Creating Your Production Account
  7. Identity and Access Management (IAM) Deep Dive
  8. STEP 4: Adding IAMADMIN to General Account
  9. STEP 4B: Adding IAMADMIN to Production Account
  10. Understanding IAM Access Keys
  11. Setting Up AWS CLI v2 Tools
  12. Best Practices and Next Steps

Introduction

Welcome to the comprehensive guide for setting up your AWS foundation! This tutorial will walk you through creating secure AWS accounts, implementing proper access management, and setting up the tools you need for effective cloud development.

What you'll learn: - How to create and secure AWS accounts properly - Implement multi-factor authentication for maximum security - Set up billing controls and budgets - Master IAM fundamentals for access management - Configure AWS CLI for development workflows

Prerequisites: - A valid email address - A credit/debit card for account verification - Basic understanding of cloud computing concepts


STEP 1: Creating Your General AWS Account

🎯 Objective

Create your first AWS account that will serve as your general-purpose learning environment.

Why Start with a General Account?

Before diving into production workloads, you need a safe space to experiment, learn, and make mistakes without consequences. Your General account serves as this sandbox environment.

Step-by-Step Account Creation

1. Navigate to AWS Console

🌐 URL: https://aws.amazon.com/

2. Click "Create an AWS Account"

  • Look for the orange "Create an AWS Account" button
  • This will redirect you to the signup page

3. Enter Account Information

📧 Email Address: your-email+aws-general@gmail.com
🏢 Account Name: "Your Name - General Learning"

💡 Pro Tip: Use the + trick with Gmail to create multiple accounts: - your-email+general@gmail.com - your-email+production@gmail.com - your-email+development@gmail.com

4. Choose Account Type

Select Personal unless you're setting this up for a business.

5. Contact Information

Full Name: [Your Full Name]
Phone Number: [Your Phone Number]
Country/Region: [Your Country]
Address: [Your Complete Address]
City: [Your City]
State/Province: [Your State]
Postal Code: [Your ZIP/Postal Code]

6. Payment Information

💳 Add a valid credit/debit card
📱 Verify your phone number via SMS

⚠️ Important Notes: - AWS will charge $1 for verification (refunded) - You won't be charged for Free Tier usage - Remove the card later if concerned about accidental charges

7. Identity Verification

  • AWS will call your phone number
  • Enter the PIN displayed on screen when prompted
  • This usually takes 1-2 minutes

8. Choose Support Plan

Select Basic Support - Free for learning purposes.

9. Complete Setup

  • Confirm your email address
  • Wait for account activation (usually instant)

Account Creation Checklist

  • [ ] Account successfully created
  • [ ] Email verification completed
  • [ ] Phone verification completed
  • [ ] Payment method added and verified
  • [ ] Support plan selected
  • [ ] Account activation confirmed

Understanding Multi-Factor Authentication (MFA)

🔐 What is MFA and Why It's Critical

Multi-Factor Authentication adds an extra layer of security by requiring: 1. Something you know (password) 2. Something you have (phone/hardware token) 3. Something you are (biometric - less common)

Why MFA is Non-Negotiable for AWS

📊 Security Statistics:
- 99.9% of account compromises could be prevented with MFA
- Root account without MFA = sitting duck for attackers
- MFA reduces risk of credential theft by 99.9%

Types of MFA Available in AWS

  • Google Authenticator (Free, iOS/Android)
  • Authy (Free, multi-device sync)
  • Microsoft Authenticator (Free, integrated with MS services)

2. Hardware MFA Device

  • YubiKey ($45-85) - Professional grade
  • Gemalto Token ($12-25) - Basic hardware token
  • Less secure due to SIM swapping attacks
  • Better than no MFA, but avoid if possible

How Virtual MFA Works

🔄 MFA Process Flow:

1. Install authenticator app on phone
2. Scan QR code from AWS
3. App generates 6-digit codes every 30 seconds
4. Enter code along with password when logging in

STEP 2: Securing Your General AWS Account

🛡️ Objective

Implement essential security measures for your newly created AWS account.

Phase 1: Secure the Root User

1. Access AWS Console

🌐 URL: https://console.aws.amazon.com/
📧 Sign in with: your-email+aws-general@gmail.com
🔑 Password: [The password you created]

2. Navigate to IAM Dashboard

Navigation Path:
Services → Security, Identity & Compliance → IAM

3. Complete Security Recommendations

The IAM Dashboard shows a security checklist. Let's complete each item:

Security Status Checklist:
□ Delete your root access keys (if any exist)
□ Activate MFA on your root account  
□ Create individual IAM users
□ Use groups to assign permissions
□ Apply an IAM password policy

Phase 2: Enable MFA on Root Account

1. Access Security Credentials

Navigation: 
Account Name (top right) → Security Credentials

2. Find Multi-Factor Authentication Section

Look for "Multi-factor authentication (MFA)" section

3. Assign MFA Device

Step 3a: Click "Assign MFA device"

Device name: root-account-mfa
MFA device: Virtual MFA device

Step 3b: Set Up Virtual MFA

Install authenticator app on your phone: - iOS: Google Authenticator / Authy - Android: Google Authenticator / Authy

Step 3c: Configure MFA 1. Click "Show QR code" 2. Scan QR code with authenticator app 3. Wait for two consecutive codes (codes change every 30 seconds) 4. Enter first code in "MFA code 1" 5. Wait 30 seconds for new code 6. Enter second code in "MFA code 2" 7. Click "Assign MFA"

Phase 3: Set Strong Password Policy

1. Navigate to Account Settings

Navigation Path:
IAM → Account settings

2. Configure Password Policy

Password Requirements:
  Minimum length: 14 characters
  Require uppercase: 
  Require lowercase:   
  Require numbers: 
  Require symbols: 
  Allow users to change password: 
  Password expiration: 90 days
  Prevent password reuse: Last 5 passwords
  Require admin reset: After 365 days

Phase 4: Verify Security Setup

1. Test MFA Login

  1. Sign out of AWS Console
  2. Sign back in with root credentials
  3. Verify MFA prompt appears
  4. Enter code from authenticator app
  5. Confirm successful login

2. Security Verification Checklist

  • [ ] MFA enabled on root account
  • [ ] MFA working correctly
  • [ ] Strong password policy implemented
  • [ ] Root access keys deleted (if any existed)
  • [ ] Security status shows improvements

🚨 Critical Security Reminders

⛔ NEVER DO:
- Share root credentials
- Use root account for daily tasks
- Save root password in browsers
- Use weak passwords
- Disable MFA

✅ ALWAYS DO:
- Use unique, strong passwords
- Keep MFA device secure
- Log out when finished
- Monitor account activity
- Use IAM users for regular tasks

STEP 3: Creating a Budget for Cost Control

💰 Objective

Set up billing alerts and budgets to prevent unexpected AWS charges.

Why Budgets Are Essential

💸 Common Cost Disasters:
- Forgot to stop EC2 instances: $500+/month
- Left RDS database running: $200+/month  
- Misconfigured data transfer: $1000+/month
- Crypto mining malware: $10,000+/month

Phase 1: Access Billing Dashboard

1. Navigate to Billing

Navigation Path:
Account Name (top right) → Billing and Cost Management

2. Enable Billing Alerts

Location: Billing Dashboard → Billing preferences
Setting: "Receive Billing Alerts" → ✅ Enable

Phase 2: Create Your First Budget

1. Navigate to Budgets

Navigation Path:
Billing Dashboard → Budgets

2. Create Budget

Click "Create budget"

3. Budget Configuration

Budget Type:

Budget Type: Cost budget
Template: Custom

Budget Details:

Budget name: "General-Account-Monthly-Budget"
Budget amount: $10.00
Time period: Monthly
Budget renewal: Recurring budget
Start month: Current month

Budget Scope:

Filters: None (monitor entire account)
Services: All AWS services
Linked accounts: Current account only

Phase 3: Configure Alerts

Alert 1: 80% Threshold

Alert type: Actual costs
Threshold: 80% of budgeted amount ($8.00)
Trigger: When actual costs exceed threshold
Email recipients: your-email+aws-general@gmail.com

Alert 2: 100% Threshold

Alert type: Actual costs  
Threshold: 100% of budgeted amount ($10.00)
Trigger: When actual costs exceed threshold
Email recipients: your-email+aws-general@gmail.com

Alert 3: Forecasted Overage

Alert type: Forecasted costs
Threshold: 100% of budgeted amount ($10.00)
Trigger: When forecasted costs exceed threshold
Email recipients: your-email+aws-general@gmail.com

Phase 4: Additional Budget Configurations

Service-Specific Budgets (Optional)

EC2 Budget:

Budget name: "EC2-Instances-Budget"
Budget amount: $5.00
Service filter: Amazon Elastic Compute Cloud

S3 Budget:

Budget name: "S3-Storage-Budget" 
Budget amount: $2.00
Service filter: Amazon Simple Storage Service

Phase 5: Billing Dashboard Setup

1. Enable Cost Explorer

Navigation: Billing → Cost Explorer
Action: Enable Cost Explorer (if not already enabled)

2. Set Up Cost and Usage Reports

Navigation: Billing → Cost & Usage Reports
Action: Create first report for detailed tracking

Budget Management Best Practices

💡 Pro Tips:

Starting Budgets:
  - Learning Account: $5-10/month
  - Development Account: $20-50/month  
  - Production Account: Based on requirements

Alert Strategy:
  - 50% threshold: Early warning
  - 80% threshold: Take action
  - 100% threshold: Emergency stop

Monitoring Frequency:
  - Daily during learning phase
  - Weekly for stable workloads
  - Real-time for production

Emergency Cost Control Measures

# Quick cost reduction checklist
📋 Emergency Actions:
- [ ] Stop all EC2 instances
- [ ] Delete unused EBS volumes  
- [ ] Remove NAT Gateways
- [ ] Delete Load Balancers
- [ ] Check CloudFormation stacks
- [ ] Review Lambda function costs
- [ ] Audit data transfer charges

DIY Challenge: Creating Your Production Account

🎯 Challenge Objective

Apply everything you've learned by independently creating a production-ready AWS account.

Why a Separate Production Account?

🏗️ Account Separation Benefits:

Security Isolation:
- Production data protected from dev experiments
- Different access controls and policies
- Reduced blast radius for incidents

Financial Control:
- Clear cost separation
- Production budget vs development budget
- Easier compliance and reporting

Operational Excellence:
- Different monitoring and alerting
- Production-grade security policies
- Formal change management

Challenge Requirements

Your mission: Create a production account with the following specifications:

Account Setup Requirements

Account Details:
  Email: your-email+aws-production@gmail.com
  Account Name: "Your Name - Production"
  Account Type: Personal (or Business if applicable)

Security Requirements:
  - Root user MFA enabled
  - Strong password policy implemented  
  - No root access keys
  - All IAM security recommendations completed

Budget Configuration:
  - Monthly budget: $25.00
  - Alerts at 50%, 80%, 100%
  - Service-specific budgets for EC2 and RDS
  - Forecasted cost alerts enabled

Step-by-Step Challenge Guide

Phase 1: Account Creation (5 minutes)

# Follow these steps independently:
1. Navigate to AWS homepage
2. Create new account with production email
3. Complete verification process
4. Choose Basic support plan
5. Verify account activation

Phase 2: Security Implementation (8 minutes)

# Security checklist to complete:
 Log into new account
 Navigate to IAM dashboard
 Enable MFA on root account
 Test MFA login functionality
 Implement password policy
 Complete all security recommendations

Phase 3: Budget Setup (5 minutes)

# Budget requirements:
 Create main budget ($25/month)
 Set up three alert thresholds
 Enable billing preferences  
 Create service-specific budgets
 Test alert email delivery

Challenge Validation

Security Validation Checklist

Root Account Security:
  - [ ] MFA device successfully configured
  - [ ] MFA login tested and working
  - [ ] Password policy implemented
  - [ ] No access keys present
  - [ ] Security status shows green checks

Account Settings:
  - [ ] Account name properly set
  - [ ] Contact information complete
  - [ ] Payment method verified
  - [ ] Support plan configured

Budget Validation Checklist

Budget Configuration:
  - [ ] Main budget created ($25/month)
  - [ ] Alert thresholds configured (50%, 80%, 100%)
  - [ ] Email alerts working
  - [ ] Billing preferences enabled
  - [ ] Cost Explorer accessible

Additional Budgets:
  - [ ] EC2 service budget created
  - [ ] RDS service budget created  
  - [ ] Forecasted alerts enabled

Common Challenge Pitfalls

⚠️ Watch Out For:

Email Issues:
  - Gmail + trick not working? Try different provider
  - Verification emails in spam folder
  - Case sensitivity in email addresses

MFA Problems:
  - Clock sync issues between phone and AWS
  - Wrong authenticator app used
  - QR code scanning problems

Budget Mistakes:
  - Forgot to enable billing preferences first
  - Alert emails not configured
  - Currency mismatch issues

Challenge Success Criteria

You've successfully completed the challenge when:

 Success Indicators:
- Production account accessible with MFA
- Budget alerts received via email
- IAM dashboard shows all green status
- Account name clearly identifies it as production
- All security recommendations completed

Next Steps After Challenge

🎓 Knowledge Gained:
- Independent AWS account creation
- Security configuration mastery
- Budget management skills
- Multi-account strategy understanding

🚀 Ready For:
- IAM user creation
- Production workload planning
- Advanced security configurations
- Cost optimization strategies

Identity and Access Management (IAM) Deep Dive

🔐 Understanding IAM Fundamentals

IAM is the cornerstone of AWS security. Before creating users and policies, let's understand the core concepts that govern how AWS security works.

IAM Core Components

🏗️ IAM Architecture:

Principal:
  - Root User (Account owner)
  - IAM Users (Individual people)
  - IAM Roles (Applications/Services)
  - Federated Users (External identity systems)

Policies:
  - Managed Policies (AWS-created or customer-managed)
  - Inline Policies (Attached directly to principal)
  - Resource-based Policies (Attached to AWS resources)

Authentication:
  - Username/Password (Console access)
  - Access Keys (Programmatic access)
  - MFA (Additional security layer)
  - Temporary credentials (Assumed roles)

Authorization:
  - Policy Evaluation Logic
  - Explicit Deny vs Allow
  - Least Privilege Principle

IAM Policy Structure Deep Dive

Anatomy of an IAM Policy

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowS3ReadAccess",
      "Effect": "Allow",
      "Principal": "*",
      "Action": [
        "s3:GetObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::my-bucket",
        "arn:aws:s3:::my-bucket/*"
      ],
      "Condition": {
        "StringEquals": {
          "aws:RequestedRegion": "us-east-1"
        }
      }
    }
  ]
}

Policy Elements Explained

Policy Components:

Version:
  Purpose: Policy language version
  Current: "2012-10-17"
  Note: Always use latest version

Statement:
  Purpose: Container for policy logic
  Type: Array of permission statements
  Required: Yes

Sid (Statement ID):
  Purpose: Optional identifier for statement
  Format: Alphanumeric string
  Use: Policy documentation and debugging

Effect:
  Options: "Allow" or "Deny"
  Default: Implicit deny if not specified
  Note: Explicit deny always wins

Principal:
  Purpose: Who the policy applies to
  Formats: AWS account, IAM user, role, service
  Note: Used in resource-based policies

Action:
  Purpose: What operations are allowed/denied
  Format: service:operation (e.g., s3:GetObject)
  Wildcards: Supported (s3:*, *)

Resource:
  Purpose: What AWS resources are affected
  Format: ARN (Amazon Resource Name)
  Wildcards: Supported for flexible access

Condition:
  Purpose: When the policy applies
  Operators: StringEquals, NumericLessThan, etc.
  Use Cases: IP restrictions, time-based access

IAM Best Practices Framework

1. Principle of Least Privilege

🔒 Least Privilege Implementation:

Start with Zero:
  - New users have no permissions
  - Grant only what's needed for job function
  - Regularly review and remove unused permissions

Granular Permissions:
  - Avoid using wildcards (*)
  - Specify exact resources when possible
  - Use conditions to limit scope

Time-based Access:
  - Temporary credentials for short-term needs
  - Regular access reviews (quarterly)
  - Automatic permission expiration

2. IAM User vs IAM Role Decision Matrix

📊 When to Use What:

Use IAM Users When:
  - Long-term credentials needed
  - Human individuals need access
  - Third-party tools requiring persistent access
  - Development team members

Use IAM Roles When:
  - AWS services need permissions
  - Temporary access required
  - Cross-account access
  - Federated users (SSO)
  - Applications running on EC2

3. Password and Access Key Management

🔑 Credential Management:

Password Policy Requirements:
  - Minimum 12 characters (14+ recommended)
  - Mixed case, numbers, symbols
  - No dictionary words
  - Regular rotation (90 days)
  - No reuse of last 12 passwords

Access Key Best Practices:
  - Rotate every 90 days
  - Never embed in code
  - Use environment variables
  - Prefer IAM roles over access keys
  - Monitor usage with CloudTrail

IAM Policy Evaluation Logic

How AWS Decides: Allow or Deny?

🧠 Policy Evaluation Flow:

1. Explicit Deny Check:
   Result: If any policy has explicit deny → DENY
   Priority: Highest (overrides everything)

2. Explicit Allow Check:
   Result: If any policy has explicit allow → ALLOW
   Requirement: Must have explicit allow to proceed

3. Default Deny:
   Result: If no explicit allow found → DENY
   Principle: Secure by default

4. Condition Evaluation:
   Timing: Applied during allow/deny evaluation
   Effect: Can convert allow to deny if conditions fail

Policy Evaluation Examples

Example 1: Simple Allow

{
  "Effect": "Allow",
  "Action": "s3:GetObject",
  "Resource": "arn:aws:s3:::my-bucket/*"
}
Result: ✅ User can read objects from my-bucket

Example 2: Explicit Deny Wins

[
  {
    "Effect": "Allow", 
    "Action": "*",
    "Resource": "*"
  },
  {
    "Effect": "Deny",
    "Action": "ec2:TerminateInstances", 
    "Resource": "*"
  }
]
Result: ✅ User has admin access BUT ❌ cannot terminate EC2 instances

Example 3: Conditional Access

{
  "Effect": "Allow",
  "Action": "s3:*",
  "Resource": "*",
  "Condition": {
    "StringEquals": {
      "aws:RequestedRegion": "us-east-1"
    }
  }
}
Result: ✅ User has S3 access only in us-east-1 region

IAM Groups Strategy

Designing Effective Group Structure

🗂️ Group Design Patterns:

Job Function Groups:
  - Developers
  - DevOps-Engineers  
  - Database-Administrators
  - Security-Team
  - Finance-Team

Environment Groups:
  - Production-Access
  - Development-Access
  - Staging-Access

Project Groups:
  - Project-Alpha-Team
  - Project-Beta-Team
  - Marketing-Campaign-Team

Hybrid Approach (Recommended):
  - Base-Developer-Access (foundation permissions)
  - Production-Database-Access (additional permissions)
  - User gets multiple group memberships

Sample Group Policies

Developer Group Policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:Describe*",
        "s3:GetObject",
        "s3:PutObject",
        "cloudformation:Describe*",
        "lambda:InvokeFunction"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:RequestedRegion": ["us-east-1", "us-west-2"]
        }
      }
    }
  ]
}

DevOps Group Policy:

{
  "Version": "2012-10-17", 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:*",
        "s3:*",
        "cloudformation:*",
        "iam:PassRole"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Deny",
      "Action": [
        "iam:CreateUser",
        "iam:DeleteUser",
        "account:CloseAccount"
      ],
      "Resource": "*"
    }
  ]
}


STEP 4: Adding IAMADMIN to General Account

🎯 Objective

Create an IAM administrative user to replace daily use of the root account.

Why Create IAMADMIN User?

🛡️ Security Benefits:

Root User Risks:
  - Cannot be restricted or limited
  - Has access to billing and account closure
  - Single point of failure if compromised
  - No granular audit trail

IAMADMIN Benefits:
  - Can be restricted if needed
  - Separate from billing functions
  - Detailed CloudTrail logging
  - Can be disabled without affecting account
  - Easier to rotate credentials

Phase 1: Create IAMADMIN User

1. Access IAM Console

Navigation Path:
AWS Console → Services → IAM

2. Navigate to Users

IAM Dashboard → Users → Add users

3. User Configuration

Step 3a: User Details

User name: iamadmin
Select AWS credential type:
  - ✅ Password - AWS Management Console access
  - ✅ Access key - Programmatic access

Step 3b: Console Password

Console password: Custom password
Password: [Create strong password - save in password manager]
Require password reset: ❌ (Uncheck for personal use)

Step 3c: Permissions Configuration

Permission Options: Add user to group
Group Selection: Create new group

Group Details:
  Group name: IAMAdmins
  Group description: Users with IAM administrative privileges

4. Attach Administrative Policy

Search and Select Policy:

Policy Name: AdministratorAccess
Policy Type: AWS managed policy
Description: Provides full access to AWS services and resources

Policy Content Preview:

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

Tags:
  Key: Role
  Value: Administrator

  Key: Environment  
  Value: General

  Key: Department
  Value: IT

6. Review and Create

Final Review Checklist: - [ ] Username: iamadmin - [ ] Console access: Enabled - [ ] Programmatic access: Enabled
- [ ] Group membership: IAMAdmins - [ ] Policies: AdministratorAccess - [ ] Tags: Added appropriately

Phase 2: Download and Secure Credentials

1. Download Credentials

Console Access:

Username: iamadmin
Password: [Your custom password]
Console URL: https://[account-id].signin.aws.amazon.com/console

Programmatic Access:

Access Key ID: AKIA...
Secret Access Key: [Long secret key]

2. Secure Credential Storage

Save Credentials Securely:

# Create credentials file (local computer)
~/.aws/credentials

[general-admin]
aws_access_key_id = AKIA...
aws_secret_access_key = [secret key]
region = us-east-1

Security Best Practices:

✅ DO:
  - Save in password manager
  - Store access keys in ~/.aws/credentials
  - Set file permissions to 600 (owner read/write only)
  - Use different passwords for each account

❌ DON'T:
  - Share credentials via email/chat
  - Store in code repositories
  - Use same password across accounts
  - Leave credentials in downloads folder

Phase 3: Test IAMADMIN Access

1. Test Console Access

Login Process: 1. Sign out of root account 2. Navigate to IAM user sign-in URL 3. Enter iamadmin credentials 4. Verify successful login 5. Check available services and permissions

2. Enable MFA for IAMADMIN

MFA Setup for User:

Navigation Path:
IAM → Users → iamadmin → Security credentials → Assigned MFA device

MFA Configuration:

Device name: iamadmin-mfa-device
MFA device type: Virtual MFA device
Authenticator app: Google Authenticator/Authy

3. Test Programmatic Access

Using AWS CLI:

# Configure AWS CLI with new credentials
aws configure --profile general-admin

# Test access
aws sts get-caller-identity --profile general-admin

# Expected output:
{
    "UserId": "AIDABC123DEFGHIJKLMN",
    "Account": "123456789012", 
    "Arn": "arn:aws:iam::123456789012:user/iamadmin"
}

Phase 4: Implement Additional Security

1. Create Custom Administrative Policy (Advanced)

Instead of using AdministratorAccess, create a more restrictive policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "*",
      "Resource": "*"
    },
    {
      "Effect": "Deny",
      "Action": [
        "account:CloseAccount",
        "account:GetAccountSummary",
        "billing:*",
        "aws-portal:*"
      ],
      "Resource": "*"
    }
  ]
}

Policy Benefits: - Full AWS service access - Blocks account closure - Restricts billing access - Maintains separation of duties

2. Set Up Access Logging

CloudTrail Configuration:

Trail Name: GeneralAccountCloudTrail
Apply to all regions: Yes
Include global services: Yes
Data events: S3 and Lambda (optional)
Management events: All

Phase 5: Documentation and Handoff

Create Access Documentation

# General Account Access Information

## Account Details
- Account ID: 123456789012
- Account Email: your-email+aws-general@gmail.com
- Account Purpose: Learning and development

## Administrative Access
- IAM User: iamadmin
- Console URL: https://123456789012.signin.aws.amazon.com/console
- MFA Required: Yes
- Access Level: Administrative (with billing restrictions)

## Security Notes
- Root account secured with MFA
- Daily operations use iamadmin user
- All activities logged via CloudTrail
- Budget alerts configured at $8 and $10

## Emergency Contacts
- Primary: [Your email]
- Backup: [Backup contact if applicable]

IAMADMIN Verification Checklist

✅ User Creation:
  - [ ] iamadmin user created successfully
  - [ ] IAMAdmins group created with proper policy
  - [ ] Console access working
  - [ ] Programmatic access working

✅ Security Configuration:
  - [ ] MFA enabled on iamadmin user
  - [ ] Strong password policy enforced
  - [ ] Access keys stored securely
  - [ ] CloudTrail logging enabled

✅ Testing:
  - [ ] Console login successful
  - [ ] AWS CLI access working
  - [ ] Permissions validated (can create/manage resources)
  - [ ] MFA login tested and working

✅ Documentation:
  - [ ] Credentials stored in password manager
  - [ ] Access documentation created
  - [ ] Emergency procedures documented

STEP 4B: Adding IAMADMIN to Production Account

🎯 Objective

Replicate the IAMADMIN setup in your production account with enhanced security measures.

Production Account Considerations

🏢 Production Differences:

Higher Security Requirements:
  - More restrictive policies
  - Enhanced monitoring
  - Formal change management
  - Compliance considerations

Operational Excellence:
  - Detailed logging and auditing
  - Automated security checks
  - Regular access reviews
  - Incident response procedures

Phase 1: Access Production Account

1. Switch to Production Account

Sign out of General account
Navigate to: https://console.aws.amazon.com/
Sign in with: your-email+aws-production@gmail.com

2. Verify Account Context

Verification Steps:
  - [ ] Check account ID in top-right corner
  - [ ] Verify account name shows "Production"
  - [ ] Confirm billing/budget setup from previous steps
  - [ ] Ensure root MFA is enabled

Phase 2: Create Production IAMADMIN

1. Navigate to IAM

Services → Security, Identity & Compliance → IAM

2. Create User with Enhanced Security

User Configuration:

User name: iamadmin-prod
AWS credential type:
  - ✅ Password - AWS Management Console access
  - ✅ Access key - Programmatic access

Console password:
  Type: Custom password
  Password: [Different from general account password]
  Require reset: ❌ Uncheck

3. Create Production Admin Group

Group Configuration:

Group name: ProductionAdmins
Description: Administrative users for production account with enhanced restrictions

4. Attach Production-Specific Policy

Option A: Use AdministratorAccess (Simple)

Policy: AdministratorAccess
Use case: Full trust environment

Option B: Custom Production Policy (Recommended)

Create custom policy for production:

```json name=ProductionAdminPolicy.json { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowAllExceptRestricted", "Effect": "Allow", "Action": "", "Resource": "" }, { "Sid": "DenyDangerousActions", "Effect": "Deny", "Action": [ "account:CloseAccount", "billing:", "aws-portal:", "iam:DeleteRole", "iam:DeleteUser", "iam:DeleteGroup", "organizations:LeaveOrganization" ], "Resource": "" }, { "Sid": "RequireMFAForCriticalActions", "Effect": "Deny", "Action": [ "ec2:TerminateInstances", "rds:DeleteDBInstance", "s3:DeleteBucket" ], "Resource": "", "Condition": { "BoolIfExists": { "aws:MultiFactorAuthPresent": "false" } } } ] }

### **Phase 3: Enhanced Security Configuration**

#### **1. Mandatory MFA Setup**

**Immediate MFA Configuration:**
```yaml
Requirement: MFA must be enabled before any production operations
Device name: iamadmin-prod-mfa
MFA type: Virtual MFA device
Backup codes: Generate and store securely

2. Access Key Rotation Policy

Create Access Key Rotation Reminder:

Strategy: 
  - Set calendar reminder for 45 days
  - Create backup access key before rotating
  - Test new key before deleting old key
  - Document rotation in access log

3. Session Duration Limits

Configure Session Settings:

Navigation: IAM → Account settings → Security Token Service (STS)

Session Configuration:
  Maximum CLI/API session duration: 8 hours
  Maximum console session duration: 12 hours
  Require MFA for role assumption: Yes

Phase 4: Production-Specific Policies

1. Create Development Team Policy

For team members who need limited production access:

```json name=ProductionReadOnlyPolicy.json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:Describe", "s3:List", "s3:GetObject", "cloudwatch:Get", "cloudwatch:List", "cloudwatch:Describe", "logs:Describe", "logs:Get", "rds:Describe" ], "Resource": "" }, { "Effect": "Allow", "Action": [ "cloudformation:List", "cloudformation:Describe", "cloudformation:Get" ], "Resource": "*" } ] }

#### **2. Create Emergency Break-Glass Role**

For emergency situations requiring elevated access:

```json name=EmergencyAccessPolicy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "*",
      "Resource": "*",
      "Condition": {
        "Bool": {
          "aws:MultiFactorAuthPresent": "true"
        },
        "StringEquals": {
          "aws:RequestedRegion": [
            "us-east-1",
            "us-west-2"
          ]
        }
      }
    }
  ]
}

Phase 5: Monitoring and Compliance

1. Enhanced CloudTrail Configuration

CloudTrail Setup:
  Trail name: ProductionCloudTrail
  Include global services: Yes
  Multi-region trail: Yes
  Log file encryption: Yes (use KMS key)
  Log file validation: Yes

Data Events:
  S3 buckets: All buckets
  Lambda functions: All functions

Insights:
  CloudTrail Insights: Enabled
  Management events: Enabled

2. Set Up CloudWatch Monitoring

Critical Metrics Dashboard:

Dashboard Name: Production-Security-Monitoring

Widgets:
  - Root account usage alerts
  - Failed login attempts
  - Unusual API call patterns  
  - MFA device changes
  - IAM policy modifications
  - Access key usage patterns

3. Automated Security Checks

AWS Config Rules:

Enable Config Rules:
  - root-access-key-check
  - mfa-enabled-for-iam-console-access
  - iam-password-policy
  - cloudtrail-enabled
  - s3-bucket-public-read-prohibited
  - s3-bucket-public-write-prohibited

Phase 6: Access Testing and Validation

1. Test Production Access

Console Access Test:

# Test login process
1. Navigate to production console URL
2. Enter iamadmin-prod credentials
3. Complete MFA challenge
4. Verify access to production resources
5. Test critical operations (with appropriate caution)

Programmatic Access Test:

# Configure production profile
aws configure --profile production-admin

# Test identity
aws sts get-caller-identity --profile production-admin

# Test access to production resources (read-only first)
aws ec2 describe-instances --profile production-admin
aws s3 ls --profile production-admin

2. Validate Security Controls

Security Validation Checklist:

✅ Access Controls:
  - [ ] MFA required and working
  - [ ] Session timeouts configured
  - [ ] Policy restrictions enforced
  - [ ] CloudTrail logging enabled

✅ Monitoring:
  - [ ] CloudWatch dashboards created
  - [ ] Security alerts configured
  - [ ] Config rules enabled
  - [ ] Budget alerts active

✅ Documentation:
  - [ ] Access procedures documented
  - [ ] Emergency contacts updated
  - [ ] Incident response plan available
  - [ ] Regular review schedule established

Production Account Final Security Review

🔒 Production Security Checklist:

Account Level:
  - [ ] Root account MFA enabled
  - [ ] Root access keys removed
  - [ ] Strong password policy enforced
  - [ ] Budget and billing alerts configured

IAM Configuration:
  - [ ] iamadmin-prod user created with MFA
  - [ ] ProductionAdmins group with appropriate policies
  - [ ] Least privilege principles applied
  - [ ] Regular access review scheduled

Monitoring & Compliance:
  - [ ] CloudTrail enabled with encryption
  - [ ] CloudWatch monitoring configured
  - [ ] AWS Config rules enabled
  - [ ] Security incident response plan documented

Operational Excellence:
  - [ ] Access procedures documented
  - [ ] Emergency contacts established
  - [ ] Regular security reviews scheduled
  - [ ] Change management process defined

Understanding IAM Access Keys

🔑 What Are IAM Access Keys?

IAM Access Keys are long-term credentials that enable programmatic access to AWS services. They consist of two parts and serve as an alternative to username/password authentication for API calls.

Access Key Components

🔐 Access Key Structure:

Access Key ID:
  Format: AKIA[16 characters]
  Example: AKIAIOSFODNN7EXAMPLE
  Visibility: Can be shared (identifies the key)
  Security: Not secret by itself

Secret Access Key:
  Format: 40 character string
  Example: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
  Visibility: Must be kept secret
  Security: Equivalent to password

When to Use Access Keys

📊 Access Key Use Cases:

✅ Appropriate Uses:
  - AWS CLI operations
  - SDK-based applications
  - CI/CD pipelines
  - Infrastructure as Code tools
  - Backup and monitoring scripts
  - Third-party integrations

❌ Avoid Access Keys For:
  - EC2 applications (use IAM roles instead)
  - Lambda functions (use execution roles)
  - Cross-account access (use roles)
  - Temporary access (use STS tokens)
  - Mobile applications (use Cognito)

Access Key Lifecycle Management

1. Creation Best Practices

🔄 Key Creation Strategy:

Initial Setup:
  - Create only when necessary
  - Download credentials immediately
  - Store in secure location
  - Test functionality before deployment

Naming Convention:
  - Use descriptive names for users
  - Include purpose in user description
  - Tag keys with metadata
  - Document key usage

2. Storage and Security

Secure Storage Methods:

# Method 1: AWS Credentials File
~/.aws/credentials

[default]
aws_access_key_id = AKIAIOSFODNN7EXAMPLE
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
region = us-east-1

[production]
aws_access_key_id = AKIAI44QH8DHBEXAMPLE
aws_secret_access_key = je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY
region = us-east-1
# Method 2: Environment Variables
export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
export AWS_DEFAULT_REGION=us-east-1
# Method 3: CI/CD Platform Secrets
GitHub Secrets:
  - AWS_ACCESS_KEY_ID
  - AWS_SECRET_ACCESS_KEY

Jenkins Credentials:
  - aws-access-key-id
  - aws-secret-access-key

Azure DevOps Variables:
  - AWS.AccessKeyId
  - AWS.SecretAccessKey

3. Rotation Strategy

🔄 Key Rotation Schedule:

Development Environment:
  Frequency: Every 90 days
  Method: Manual rotation acceptable

Production Environment:
  Frequency: Every 30-60 days
  Method: Automated rotation preferred

High-Security Environment:
  Frequency: Every 30 days
  Method: Automated with monitoring

Rotation Process:

# Step 1: Create new access key (keep old key active)
aws iam create-access-key --user-name iamadmin

# Step 2: Update applications with new key
# Update ~/.aws/credentials or environment variables

# Step 3: Test new key functionality
aws sts get-caller-identity

# Step 4: Delete old access key
aws iam delete-access-key --user-name iamadmin --access-key-id AKIAI44QH8DHBEXAMPLE

Access Key Security Best Practices

1. Never Embed in Code

❌ Bad Examples:

Hardcoded in Application:
  aws_access_key_id = "AKIAIOSFODNN7EXAMPLE"
  aws_secret_access_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"

Committed to Git:
  config/aws_credentials.py
  .env files with credentials
  Docker images with credentials

Configuration Files in Public Repos:
  docker-compose.yml with keys
  terraform files with keys
  kubernetes manifests with keys
✅ Good Examples:

Environment Variables:
  process.env.AWS_ACCESS_KEY_ID
  os.getenv('AWS_ACCESS_KEY_ID')

Configuration Management:
  AWS Systems Manager Parameter Store
  HashiCorp Vault
  Kubernetes Secrets

Instance Profiles (Preferred):
  EC2 instances with IAM roles
  ECS tasks with execution roles
  Lambda functions with execution roles

2. Monitoring and Auditing

CloudTrail Monitoring:

🔍 Key Usage Monitoring:

Track These Events:
  - CreateAccessKey
  - DeleteAccessKey
  - UpdateAccessKey
  - AssumeRole (for role-based access)

Monitor For:
  - Unusual geographic locations
  - High-volume API calls
  - Failed authentication attempts
  - Access outside business hours

CloudWatch Metrics:

# Create custom metric for access key usage
aws logs put-metric-filter \
  --log-group-name CloudTrail/MyCloudTrail \
  --filter-name AccessKeyUsage \
  --filter-pattern '[version, account, time, event, eventName="AssumeRole*"]' \
  --metric-transformations \
    metricName=AccessKeyUsage,metricNamespace=Security,metricValue=1

3. Access Key Permissions

Principle of Least Privilege:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": "arn:aws:s3:::my-specific-bucket/*"
    },
    {
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::my-specific-bucket"
    }
  ]
}

Conditional Access:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "*",
      "Resource": "*",
      "Condition": {
        "IpAddress": {
          "aws:SourceIp": ["203.0.113.0/24", "198.51.100.0/24"]
        },
        "DateGreaterThan": {
          "aws:CurrentTime": "2025-01-01T00:00:00Z"
        },
        "DateLessThan": {
          "aws:CurrentTime": "2025-12-31T23:59:59Z"
        }
      }
    }
  ]
}

Troubleshooting Access Key Issues

Common Problems and Solutions

🔧 Troubleshooting Guide:

Problem: "Invalid Access Key ID"
Causes:
  - Typo in access key ID
  - Key doesn't exist
  - Key belongs to different account
Solutions:
  - Verify key ID spelling
  - Check IAM console for key existence
  - Confirm account context

Problem: "Access Denied"
Causes:
  - Insufficient permissions
  - Explicit deny in policy
  - Resource doesn't exist
  - Regional restrictions
Solutions:
  - Review attached policies
  - Check for deny statements
  - Verify resource ARNs
  - Confirm region settings

Problem: "Signature Mismatch"
Causes:
  - Incorrect secret key
  - Clock skew issues
  - Character encoding problems
Solutions:
  - Regenerate and update secret key
  - Synchronize system clock
  - Check for special characters

Testing Access Key Functionality

# Test basic connectivity
aws sts get-caller-identity

# Test specific service access
aws s3 ls

# Test with verbose output for debugging
aws s3 ls --debug

# Test with specific profile
aws s3 ls --profile production-admin

# Validate permissions for specific action
aws iam simulate-principal-policy \
  --policy-source-arn arn:aws:iam::123456789012:user/iamadmin \
  --action-names s3:GetObject \
  --resource-arns arn:aws:s3:::my-bucket/my-key

Migration from Access Keys to Roles

When to Migrate

🚀 Migration Scenarios:

EC2 Applications:
  From: Access keys stored on instance
  To: IAM instance profile/role
  Benefit: Automatic credential rotation

Lambda Functions:
  From: Access keys in environment variables
  To: Lambda execution role
  Benefit: Integrated permissions management

Cross-Account Access:
  From: Cross-account user with access keys
  To: Cross-account role assumption
  Benefit: Temporary credentials, better audit trail

CI/CD Pipelines:
  From: Long-lived access keys
  To: OIDC-based role assumption
  Benefit: Short-lived tokens, no stored secrets

Migration Steps

# Step 1: Create IAM role with required permissions
aws iam create-role --role-name MyApplicationRole \
  --assume-role-policy-document file://trust-policy.json

# Step 2: Attach policies to role
aws iam attach-role-policy \
  --role-name MyApplicationRole \
  --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

# Step 3: Update application to use role
# (Implementation depends on service - EC2, Lambda, etc.)

# Step 4: Test role-based access
aws sts assume-role --role-arn arn:aws:iam::123456789012:role/MyApplicationRole \
  --role-session-name test-session

# Step 5: Remove access keys
aws iam delete-access-key --user-name old-user \
  --access-key-id AKIAIOSFODNN7EXAMPLE

Setting Up AWS CLI v2 Tools

🛠️ Objective

Install, configure, and optimize AWS CLI v2 for efficient cloud management across multiple accounts.

Why AWS CLI v2?

🆚 CLI v1 vs v2 Comparison:

Performance:
  v1: Python-based, slower startup
  v2: Compiled binary, faster execution

Features:
  v1: Basic functionality
  v2: Enhanced features, better error handling

Installation:
  v1: pip install (dependency conflicts possible)
  v2: Standalone installer (no conflicts)

Support:
  v1: Maintenance mode
  v2: Active development, new features

Phase 1: Installation

1. Install AWS CLI v2

Windows Installation:

# Download installer
Invoke-WebRequest -Uri "https://awscli.amazonaws.com/AWSCLIV2.msi" -OutFile "AWSCLIV2.msi"

# Run installer
Start-Process msiexec.exe -ArgumentList '/i AWSCLIV2.msi /quiet' -Wait

# Verify installation
aws --version

macOS Installation:

# Using Homebrew (recommended)
brew install awscli

# Or download installer
curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
sudo installer -pkg AWSCLIV2.pkg -target /

# Verify installation
aws --version

Linux Installation:

# Download and install
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

# Update PATH if needed
export PATH=$PATH:/usr/local/bin

# Verify installation
aws --version
# Expected output: aws-cli/2.x.x Python/3.x.x

Docker Installation:

# Run AWS CLI in Docker container
docker run --rm -it amazon/aws-cli:latest --version

# Create alias for convenience
alias aws='docker run --rm -it -v ~/.aws:/root/.aws amazon/aws-cli:latest'

2. Verify Installation

# Check version (should show v2.x.x)
aws --version

# Check help system
aws help

# Test basic functionality
aws sts get-caller-identity --help

Phase 2: Initial Configuration

1. Configure Default Profile

# Interactive configuration
aws configure

# You'll be prompted for:
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-east-1
Default output format [None]: json

2. Configuration Files Overview

Credentials File (~/.aws/credentials):

[default]
aws_access_key_id = AKIAIOSFODNN7EXAMPLE
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

[general-admin]
aws_access_key_id = AKIAI44QH8DHBEXAMPLE
aws_secret_access_key = je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY

[production-admin]
aws_access_key_id = AKIAI55RH9DHCEXAMPLE
aws_secret_access_key = kf8NuHbDmxCG/3Aq0Vtl/j4zDp9owcFXAMPLEKEY

Config File (~/.aws/config):

[default]
region = us-east-1
output = json

[profile general-admin]
region = us-east-1
output = table
cli_pager = 

[profile production-admin]
region = us-east-1
output = json
cli_pager = less
mfa_serial = arn:aws:iam::123456789012:mfa/iamadmin-prod

Phase 3: Multi-Account Configuration

1. Set Up Named Profiles

# Configure general account profile
aws configure --profile general-admin
# Enter general account access keys

# Configure production account profile
aws configure --profile production-admin
# Enter production account access keys

2. Profile-Specific Settings

Advanced Configuration Options:

# ~/.aws/config
[profile general-admin]
region = us-east-1
output = table
cli_pager = 
cli_follow_redirects = false
cli_timestamp_format = iso
max_attempts = 3
retry_mode = adaptive

[profile production-admin]
region = us-east-1
output = json
cli_pager = less
parameter_validation = true
tcp_keepalive = true
max_bandwidth = 100MB/s
max_concurrent_requests = 10

3. Environment-Specific Aliases

# Add to ~/.bashrc or ~/.zshrc
alias aws-gen='aws --profile general-admin'
alias aws-prod='aws --profile production-admin'

# Usage examples
aws-gen s3 ls
aws-prod ec2 describe-instances

Phase 4: Testing and Validation

1. Test Each Profile

# Test default profile
aws sts get-caller-identity

# Test general admin profile
aws sts get-caller-identity --profile general-admin

# Test production admin profile
aws sts get-caller-identity --profile production-admin

Expected Output Examples:

{
    "UserId": "AIDABC123DEFGHIJKLMN",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/iamadmin"
}

2. Test Service Access

# Test S3 access
aws s3 ls --profile general-admin

# Test EC2 access
aws ec2 describe-regions --profile general-admin

# Test IAM access (admin required)
aws iam list-users --profile general-admin

3. Test Cross-Region Operations

# List resources in different regions
aws ec2 describe-instances --region us-east-1 --profile general-admin
aws ec2 describe-instances --region us-west-2 --profile general-admin

# Use region-specific profiles
aws s3 ls --region eu-west-1 --profile general-admin

Phase 5: Advanced CLI Features

1. Output Formatting

# JSON output (default)
aws ec2 describe-instances --output json

# Table output (human-readable)
aws ec2 describe-instances --output table

# Text output (for scripting)
aws ec2 describe-instances --output text

# YAML output (v2 feature)
aws ec2 describe-instances --output yaml

2. JMESPath Queries

# Basic query
aws ec2 describe-instances --query 'Reservations[*].Instances[*].InstanceId'

# Complex query with filtering
aws ec2 describe-instances \
  --query 'Reservations[*].Instances[?State.Name==`running`].[InstanceId,InstanceType,PublicIpAddress]' \
  --output table

# Count running instances
aws ec2 describe-instances \
  --query 'length(Reservations[*].Instances[?State.Name==`running`])'

3. CLI Pagination

# Manual pagination
aws s3api list-objects-v2 --bucket my-bucket --max-items 100

# Automatic pagination (default behavior)
aws ec2 describe-instances

# Disable pagination
aws ec2 describe-instances --no-paginate

# Custom page size
aws ec2 describe-instances --page-size 10

Phase 6: Security and Best Practices

1. MFA Integration

Configure MFA for CLI:

# ~/.aws/config
[profile production-admin]
region = us-east-1
output = json
mfa_serial = arn:aws:iam::123456789012:mfa/iamadmin-prod

Use MFA with CLI:

# Get session token with MFA
aws sts get-session-token \
  --serial-number arn:aws:iam::123456789012:mfa/iamadmin-prod \
  --token-code 123456 \
  --duration-seconds 3600

# Use temporary credentials
export AWS_ACCESS_KEY_ID=ASIAIOSFODNN7EXAMPLE
export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
export AWS_SESSION_TOKEN=AQoDYXdzEJr...<long-token-string>

2. Secure Configuration

# Set proper file permissions
chmod 600 ~/.aws/credentials
chmod 600 ~/.aws/config

# Verify permissions
ls -la ~/.aws/
# Should show: -rw------- (600)

3. Credential Helper Scripts

```bash name=aws-mfa-helper.sh

!/bin/bash

MFA Helper Script

PROFILE=$1 MFA_TOKEN=$2

if [ -z "$PROFILE" ] || [ -z "$MFA_TOKEN" ]; then echo "Usage: $0 " exit 1 fi

Get MFA serial from config

MFA_SERIAL=$(aws configure get mfa_serial --profile $PROFILE)

if [ -z "$MFA_SERIAL" ]; then echo "Error: MFA serial not configured for profile $PROFILE" exit 1 fi

Get temporary credentials

TEMP_CREDS=$(aws sts get-session-token \ --profile $PROFILE \ --serial-number $MFA_SERIAL \ --token-code $MFA_TOKEN \ --duration-seconds 3600 \ --output json)

Extract credentials

ACCESS_KEY=$(echo $TEMP_CREDS | jq -r '.Credentials.AccessKeyId') SECRET_KEY=$(echo $TEMP_CREDS | jq -r '.Credentials.SecretAccessKey') SESSION_TOKEN=$(echo $TEMP_C

Bình luận