Introduction to Amazon CloudWatch (CW)
Amazon CloudWatch – Components and Architecture

- CloudWatch collects and manages operational data, providing monitoring and operational management.
- Operational data includes service performance, metrics, logs, and more.
- It is a core support service used by most AWS services.
- CloudWatch is a public AWS service.
Main Components of CloudWatch
- CloudWatch Metrics
- Provides the core metrics service.
- Examples: CPU utilization of an EC2 instance, disk usage of an on-premises server.
- Can collect metrics from AWS services, custom applications, or on-premises systems.
- Some metrics are gathered natively by AWS.
- A CloudWatch Agent is required to collect:
- Non-native AWS metrics (e.g., internal processes in EC2 instances)
- Metrics from outside AWS
- Metrics should be organized and separated to avoid confusion.
- CloudWatch Logs
- Collects logs from AWS services, applications, or on-premises infrastructure.
- Some logs are generated natively; others require the CloudWatch Agent.
- CloudWatch Alarms
- Trigger notifications (via Amazon SNS) or events based on monitored metrics.
- Example: Send an SMS when an EC2 instance’s CPU usage exceeds 90%.
- Billing alarms are also created in CloudWatch, sending notifications when costs exceed a threshold.
- CloudWatch Events (now Amazon EventBridge)
- Integrates with AWS services and scheduled events.
- Generates events that can trigger actions, such as sending notifications.
- Events are generated based on:
- Conditions (e.g., EC2 instance creation or termination)
- Schedules (e.g., specific times or recurring schedules)
Amazon CloudWatch – Key Concepts

- Datapoint = combination of a timestamp and a value.
- Example: CPU usage = 98.3% at 08:45:45 on 2019-12-03.
- Metric = a time-ordered sequence of datapoints.
- Examples: CPU usage, network I/O, disk I/O.
- Metrics are not necessarily tied to a single instance; for example, CPU usage may represent all EC2 instances by default unless filtered.

- Namespace = container for related monitoring data.
- Organizes metrics to avoid clutter.
- Can use any valid naming convention.
- Example:
AWS/contains all AWS metrics, andAWS/EC2contains all EC2-related metrics.
- Dimensions = criteria to separate datapoints of the same metric into different perspectives.
- Example: Within
AWS/EC2, dimensions may separate metrics for Instance A and Instance B. - Dimensions are flexible and powerful for filtering and analysis.
- Example: Within

- Alarms perform actions when a metric reaches a specified threshold.
- Example: Send a notification when costs exceed a budget.
- States:
INSUFFICIENT DATA– initial stateOK– metric is within the thresholdALARM– threshold exceeded; alarm triggers actions- Notifications are sent using Amazon SNS when the state is
ALARM.
Introduction to AWS CloudFormation (CFN)
IaC Basics and AWS CloudFormation
- IaC (Infrastructure as Code)
- Enables creation, updating, and deletion of infrastructure using code or templates.
- Code and templates are consistent and repeatable, which:
- Reduces human errors
- Speeds up provisioning and deletion compared to manual methods
- AWS CloudFormation (CFN)
- AWS’s official IaC service.
- Templates are written in YAML or JSON to interact with AWS infrastructure.
- External IaC tools like Terraform or AWS CDK are popular; they translate into CFN templates to manage AWS resources.
CFN Templates – Components and Examples
- By default, CFN templates are stored in an S3 bucket with the prefix
CF.- Do not confuse CFN (CloudFormation) with CF (CloudFront).
- Resources – AWS resources to create, update, or delete.
- Examples: VPCs, S3 buckets, EC2 instances.
- Mandatory component – a template without resources does nothing.
- Resources in templates are logical resources, not physical.
- AWSTemplateFormatVersion – Version of the template.
- Description – Optional text explaining the template.
- Must appear after
AWSTemplateFormatVersionif included.
- Must appear after
- Metadata – Defines how the template appears in the AWS console.
- Parameters – Fields prompting users to provide required input values.
- Mappings – Key-value pairs used for lookups within the template.
- Conditions – Define criteria for resource creation (e.g., create a resource only if in a PROD environment).
- Outputs – Messages or values returned when the template is applied (e.g., “EC2 instance created”).
- Intrinsic Functions – Built-in functions used in templates:
LatestAmiId– Fetch the most recent AMI in a region.!Ref– Reference an existing resource.!GetAtt– Retrieve a specific attribute from a resource.
- Template Examples (YAML & JSON): CFN Template Examples
CFN Stacks

- A CFN template contains logical resources and other components.
- CFN Stack – The active representation of all resources defined in a template.
- Created from a template.
- Can be executed in an AWS account to create, update, or delete infrastructure.
- Each logical resource in the stack corresponds to a physical resource in AWS.
Syncing Logical and Physical Resources
- Physical Resource – Exists in AWS infrastructure and is visible in the console.
- Example: Running EC2 instance with ID
i-1234567890abcdef0.
- Example: Running EC2 instance with ID
- Logical Resource – Defined in CFN templates and stacks.
- Does not exist outside of CFN templates/stacks.
- Includes a type (e.g.,
AWS::EC2::Instance) and properties (e.g.,ImageID,KeyName). - Can be synced to the corresponding physical resource.
- CloudFormation’s Role
- Keeps logical and physical resources synchronized.
- Automates infrastructure management.
- Allows approvals before committing changes.
- Enables quick deployment of one-off resources.
- Deleting a stack removes both logical and physical resources, ensuring automatic cleanup.
- Widely used in labs and demos for SAA-C03 preparation.

Introduction to AWS Lambda
AWS Lambda – Key Concepts
- Function-as-a-Service (FaaS) – designed for short-lived, focused code execution.
- A Lambda function is the unit of code executed by AWS Lambda.
- “A Lambda” is commonly used to refer to “a Lambda function.”
- Each function must specify a Runtime Environment (RTE) (e.g., Python 3.8) before execution.
- Memory is directly configured, while vCPU is indirectly determined based on memory.
- When triggered, the function executes in the selected RTE.
- Billing is based only on the compute consumed during execution.
- Ideal for serverless and event-driven architectures (EDA).
- Cost-effective: the first million invocations are free under AWS Free Tier, and subsequent invocations are inexpensive.
AWS Lambda – Architecture

- A Lambda function consists of code, configuration, and runtime package.
- Includes programming language, deployment package (downloaded and executed at runtime), and allocated resources.
- Colloquially, “Lambda” may refer only to the code, but the function is more than just the code.
- Supported Runtimes: Python, Ruby, Java, Node.js, and more.
- Lambda Layers allow custom runtimes (e.g., Rust via community support).
- Invocation Behavior:
- Each invocation creates a new RTE. Code is loaded, executed, and terminated.
- Subsequent invocations usually start with a fresh RTE, although some configurations can reuse RTE components.
- Functions are stateless; no data persists between invocations.
- Docker Considerations:
- Traditional Docker is considered an anti-pattern for Lambda.
- Lambda supports Docker images, but these are specialized for Lambda, not standard containerized environments.
- Resource Allocation:
- Memory: 128MB–10240MB (1MB increments).
- vCPU: 1 vCPU per 1769MB of memory (scales linearly with memory).
- Temporary disk: 512MB mounted at
/tmp, can scale up to 10240MB. Data is wiped on each invocation.
- Timeout: Maximum 900 seconds (15 minutes). Functions requiring longer execution should use services like AWS Step Functions.
- Execution Role: IAM role that governs permissions and security for the function.
AWS Lambda – Common Use Cases
- Serverless Applications: e.g., S3 + API Gateway + Lambda
- File Processing: e.g., watermarking images uploaded to S3
- Database Triggers: e.g., DynamoDB Streams invoking Lambda on data changes
- Scheduled Tasks: Using EventBridge or CloudWatch Events to run periodic functions
- Real-time Data Processing: e.g., Kinesis Data Streams triggering Lambda functions
Demo: Create and Execute a Lambda Function
- Deploy CloudFormation Stack to spin up two EC2 instances:
- Create Execution Role in IAM or during Lambda creation.
- Example JSON for EC2 start/stop permissions:
{
“Version”: “2012-10-17”,
“Statement”: [
{
“Effect”: “Allow”,
“Action”: [
“logs:CreateLogGroup”,
“logs:CreateLogStream”,
“logs:PutLogEvents”
],
“Resource”: “arn:aws:logs:::” }, { “Effect”: “Allow”, “Action”: [ “ec2:Start“,
“ec2:Stop” ], “Resource”: ““
}
]
}

- Create Lambda Function:
- Provide a name and select runtime (e.g., Python 3.9).
- Assign the execution role created in step 2.
- Add Code to the function:
Stop EC2 Instances Example:

import boto3
import os
region = ‘us-east-1’
ec2 = boto3.client(‘ec2’, region_name=region)
def lambda_handler(event, context):
instances = os.environ[‘EC2_INSTANCES’].split(“,”)
ec2.stop_instances(InstanceIds=instances)
print(‘Stopped instances: ‘ + str(instances))
- Set Environment Variables:
- Include
EC2_INSTANCESwith instance IDs (comma-separated).
- Include
- Test the Function:
- Click “Test” in the console; verify EC2 instances stop.
- After the function executes successfully, output will be displayed in the console and the EC2 instances will be stopped. Confirm this by checking the EC2 console.
- Create another function using the same approach to start the EC2 instances. Run or test the function and verify in the EC2 console that the instances have started.
Start EC2 Instances Example:

import boto3
import os
region = ‘us-east-1’
ec2 = boto3.client(‘ec2’, region_name=region)
def lambda_handler(event, context):
instances = os.environ[‘EC2_INSTANCES’].split(“,”)
ec2.start_instances(InstanceIds=instances)
print(‘Started instances: ‘ + str(instances))
9. Clean-up: delete the created functions, then delete the CloudFormation stack
Introduction to Amazon Route 53 (R53)
Amazon Route 53 (R53) – Core Concepts
- DNSaaS (DNS as a Service): an AWS-managed DNS offering
- A global service
- Uses a single database that is replicated and accessible across all regions
- Designed to be globally resilient
- No region selection is required in the AWS console
- Two primary features:
- R53 Registered Domains
- Route 53 can function as a domain name registrar
- R53 Hosted Zones
- Route 53 can also act as a DNS hosting provider
- R53 Registered Domains
- Note that in addition to domain registration and renewal costs, there are charges for maintaining hosted zones
R53 Registered Domains

- Route 53 maintains relationships with major TLD registries (such as
.com,.io,.net)- For example, PIR (Public Interest Registry) manages the
.orgTLD
- For example, PIR (Public Interest Registry) manages the
- Process for registering a new domain (for example,
animals4life.org):- Route 53 checks whether the domain name is available
- If available, the customer agrees to the terms and purchases the domain through Route 53
- Route 53 creates a ZoneFile, which stores the domain’s DNS data
- Route 53 assigns AWS-managed name servers for the DNS zone
- Always four name servers
- A hosted zone is created
- The ZoneFile is stored across the four assigned name servers
- Entries are created in both Registered Domains and Hosted Zones referencing these servers
- Route 53 communicates with the TLD registry (for example, PIR for
.org)- The TLD’s NS records are updated to point to the Route 53 name servers
- These four servers become authoritative for the domain
- Registering a domain is not required to complete CLF-C02 or SAA-C03 coursework. You can simply observe the demonstrations. However, for projects such as the Cloud Resume Challenge, owning a domain is recommended and often necessary.
- Transfer lock (enabled by default)
- Prevents the domain from being transferred out of Route 53
- If a hosted zone is deleted and recreated, the name server records in Registered Domains must be updated to reference the new servers
- Failure to do so will cause DNS resolution issues
R53 Hosted Zones
- Route 53 stores DNS zones across four AWS-managed name servers
- These servers hold DNS records (RRSETs)
- Network visibility options:
- Public Hosted Zones
- ZoneFile is publicly accessible
- Part of the global DNS system
- Reachable from the public internet
- Private Hosted Zones
- ZoneFile is private
- Associated with specific VPCs
- Accessible only within those VPCs
- Commonly used for internal or sensitive DNS records
- Public Hosted Zones
- Costs:
- Monthly fee for each hosted zone
- Small charge per DNS query
- Query costs can become significant for high-traffic environments and should be monitored
Identity, Access, and Organizational Management
AWS IAM Basics
Identity and Access Management (IAM) Service
- AWS IAM is a fundamental AWS service used to manage identities
- It performs three primary functions:
- Manages identities → IAM acts as an Identity Provider (IdP)
- Authenticates identities → verifies that an entity is who it claims to be
- Authorizes access → grants or denies permissions based on defined policies
- No cost (free service)
- A public and global service, providing high availability and resilience
- IAM data is securely replicated across all AWS Regions
- It performs three primary functions:
- IAM provides full administrative capabilities within an account, but it only manages internal identities
- It does not have direct authority over external accounts or identities
- Each AWS account contains its own IAM instance, with a separate identity database
- This instance operates independently from IAM instances in other accounts
- An AWS account places complete trust in its own IAM system
- IAM can manage nearly all operations within an account
- Exceptions include billing management and account termination, which are restricted to the root user
- IAM also supports:
- Multi-Factor Authentication (MFA)
- Identity Federation
- External identities (such as social logins like Facebook or Google, or corporate directory services like Active Directory) can be used to access AWS resources indirectly
Root User of the Account (Account Root User)
- The account root user is the original identity created with an AWS account
- It is tied to the account’s email address
- The account fully trusts the root user, granting complete and unrestricted access
- In practice, the account and its root user are closely linked
- The root user is not an IAM identity, meaning IAM policies do not apply to it
- Best practice: avoid using the root user for routine tasks
- Use it only for specific actions that require root-level permissions
- Security best practice: apply the principle of least privilege
- Grant users only the permissions they need to perform their responsibilities
- Restrict all unnecessary access to reduce risk

IAM Identities and IAM Policies
- IAM enables the creation of additional identities within an AWS account, known as IAM identities:
- IAM users: represent individuals or applications that require long-term access to the account
- Each user typically corresponds to a specific identifiable entity
- They use long-term credentials, such as a username and password and/or access keys
- IAM groups: collections of IAM users with similar roles or responsibilities
- For example, teams like development, finance, or HR
- IAM roles: used by AWS services or external entities to gain access to an account
- Ideal when the number of users or entities is not fixed or predictable
- They provide temporary (short-term) credentials
- IAM users: represent individuals or applications that require long-term access to the account
- An IAM policy is a document or object that can be attached to an IAM identity
- It defines permissions by allowing or denying access to AWS services and resources
- The account applies these permissions by trusting the identity and its assigned policies
- Policies are written in JSON format

Demo: Creating an IAM Admin User in an AWS Account
- IAM users access an AWS account through a sign-in URL:
- Format:
https://<account-id>.signin.aws.amazon.com.console- The account ID is a numeric identifier
- You can also use an account alias, which is easier to remember
- Must be globally unique
- Provides a more user-friendly login URL:
https://<account-alias>.signin.aws.amazon.com.console
- Format:
- In this demonstration, a new IAM user with administrator-level permissions is created, named
iamadmin- This allows regular tasks to be performed without using the root user
- The root user cannot be restricted, deleted, or recreated, making it unsafe for everyday use
- This allows regular tasks to be performed without using the root user
- Steps to create an IAM user:
- Navigate to: IAM → Users → Add Users
- Set a username (e.g.,
iamadmin)- The username must be unique within the account, but not globally
- By default, a new IAM user has no permissions, so access must be granted during setup
- For the
iamadminuser, attach the policy namedAdministratorAccess- This policy provides full access to the account, except for certain actions reserved for the root user (such as closing the account)
- For the
- After signing in as the
iamadminuser, the username will appear in the top-right corner of the AWS Management Console

- Enable Multi-Factor Authentication (MFA) for the
iamadminuser to strengthen account security.
IAM Access Keys
Long-term and Short-term Credentials
- Credentials are pieces of information recognized by AWS and identities that enable authentication (logging in to an AWS account)
- Long-term credentials remain valid until they are manually changed
- Examples include username and password and IAM access keys
- These must be updated manually by the owner when needed
- Short-term credentials are temporary and expire after a limited period
- Users or services must regularly request new credentials for continued access
- Long-term credentials remain valid until they are manually changed
- The root user and IAM users rely on long-term credentials, while IAM roles use temporary credentials
- Credentials consist of two parts:
- A public identifier
- A private secret
- Example: username (public) and password (private), with MFA acting as an additional private factor
IAM Access Keys
- Access to AWS through the CLI and APIs is commonly performed using IAM access keys
- IAM access keys are a type of long-term credential in AWS
- Each key pair includes:
- Access Key ID (public) (e.g.,
AKIAIOSF0DNN7EXAMPLE) - Secret Access Key (private) (e.g., a longer, more complex string)
- This secret is shown only once at creation and cannot be retrieved again
- Access Key ID (public) (e.g.,
- Each key pair includes:

- Access keys can be:
- Created
- Deleted
- Activated or deactivated
- Newly created keys are active by default
- Access keys cannot be modified after creation
- Instead, they should be rotated by deleting the old keys and generating new ones
- An IAM user can have:
- Zero or one username/password pair
- Some users are intended only for CLI or API access and may not require a password
- Up to two access key pairs
- This supports smooth key rotation without downtime
- Zero or one username/password pair
- Although the root user can have access keys, this is not recommended
- The root user should not be used for regular operations, especially for CLI or API access
Demo: Creating Access Keys and Configuring AWS CLI v2
- Create access keys:
- Go to: Account menu → Security Credentials → Create Access Key
- Download and securely store the keys (for example, using the CSV file option)
- Install AWS CLI v2 tools:
- Follow the official installation guide
- Verify installation by running:
aws→ should display usage instructionsaws --version→ confirms the installed version (ensure it is version 2 or higher)
- AWS CLI v2 supports profiles for managing multiple configurations:
aws configure→ sets up the default profileaws configure --profile iamadmin-general→ creates a named profile- Provide:
- Access Key ID and Secret Access Key
- Default region (e.g.,
us-east-1) - Default output format
- Provide:
- Example command:
aws s3 ls→ lists all S3 buckets in the account- Commonly used to verify successful CLI access
- When using a named profile:
aws s3 ls --profile iamadmin-general
- After configuration, it is recommended to delete downloaded credential files (such as CSV files) from your local machine for security purposes
IAM Permission Policies
IAM Policy
- An IAM policy is a document that defines permissions for accessing AWS resources and performing actions
- Written in JSON format
- Specifies whether access is allowed or denied for resources and operations
- It is important to understand the structure of policies and how to read and create them
Policy Statements
- IAM policies consist of one or more permission statements
- These statements enable fine-grained control over access
- Each statement includes the following components:
- SID (Statement ID):
- A human-readable identifier describing the purpose of the statement
- Optional, but recommended for clarity
- Resource:
- Specifies the AWS resources affected by the statement
- Defined using ARNs (Amazon Resource Names)
- Supports wildcards (
*) to match multiple resources - Example:
arn:aws:s3:::catgifs/*refers to all objects within thecatgifsbucket
- Action:
- Lists the operations that are allowed or denied
- Based on AWS API actions
- Supports wildcards (
*) - Example:
s3:ListBuckets→ lists all S3 buckets in the accounts3:*→ allows all S3 actions
- Effect:
- Determines the result: Allow or Deny
- SID (Statement ID):
- A statement can be understood as a rule:
- If the action and resource match, then the specified effect is applied

- Example summary:
- One statement allows all S3 actions on all resources
- Another statement denies all S3 actions on the
catgifsbucket and its contents
Permission Evaluation Logic
- Permission decisions follow this priority:
- Explicit Deny overrides everything
- Explicit Allow is applied if no deny exists
- Otherwise, access is denied by default
- In short: Explicit Deny > Explicit Allow > Implicit Deny
- Implicit Deny:
- All access is denied by default unless explicitly allowed
- To gain access, a user must have an explicit allow and no conflicting deny
- Exception:
- The root user has full access and cannot be restricted by IAM policies
- However, Service Control Policies (SCPs) can still impose restrictions at the account level
Applying Permission Logic (Example)

- A policy includes:
- One statement that allows all S3 actions on all resources
- Another statement that denies all S3 actions on the
catgifsbucket and its objects
- If this policy is attached to an IAM user:
- The user cannot list EC2 instances
- No explicit allow exists, so access is implicitly denied
- The user can list S3 buckets
s3:ListBucketsis explicitly allowed, and there is no deny for this action- The
catgifsbucket will still appear in the list because the action applies at the account level, not within the bucket
- The user cannot access objects inside the
catgifsbucket- Even though there is a general allow, the explicit deny for that bucket overrides it
- The user cannot list EC2 instances
IAM Policy Types
Attachment Types: Identity Policies vs Resource Policies

- IAM Identity Policies are attached to IAM identities (users, groups, or roles)
- Define permissions from the identity’s perspective
- Can be either inline or managed
- AWS evaluates which policies are attached to an authenticated identity and processes all related statements
- IAM Resource Policies are attached directly to AWS resources
- Examples include S3 bucket policies or SNS topic policies
- Define permissions from the resource’s perspective
- Must include a Principal element in each statement
- Specifies which identities the policy applies to (internal or external)
- Can grant or deny access to:
- Identities from other AWS accounts
- Anonymous users
- Unauthenticated entities
- AWS evaluates all applicable policies (both identity and resource policies) when determining access to a resource or action
Management Types for Identity Policies: Inline vs Managed Policies

- Inline Policies
- Attached to a single identity within one account
- Designed for specific or exceptional use cases
- Example: granting one developer access to a particular S3 bucket while restricting others
- Managed Policies
- Can be attached to multiple identities and reused across accounts
- Recommended as the default approach
- Benefits:
- Reusable across many users, groups, or roles
- Easier to manage, since updates apply to all attached identities
- Types of managed policies:
- AWS-managed policies
- Predefined and maintained by AWS
- Cover common use cases
- Example:
AdministratorAccess - May not always meet specific requirements
- Customer-managed policies
- Created and maintained by the user
- Allow customization to meet exact business needs
- AWS-managed policies
Amazon Resource Name (ARN)
- An ARN (Amazon Resource Name) is a globally unique identifier for an AWS resource
- It uniquely identifies a resource across all AWS accounts and regions
- ARN formats vary slightly depending on the service:
arn:partition:service:region:account-id:resource-id
arn:partition:service:region:account-id:resource-type/resource-id
arn:partition:service:region:account-id:resource-type:resource-id
- The
<partition>is typicallyaws - Examples:
arn:aws:iam::aws:policy/IAMUserChangePassword- Refers to an AWS-managed IAM policy
- No region or account ID is required because IAM is a global service and the policy is shared
arn:aws:s3:::catgifs- Refers only to the S3 bucket named
catgifs
- Refers only to the S3 bucket named
arn:aws:s3:::catgifs/*- Refers to all objects within the
catgifsbucket
- Refers to all objects within the
- Important distinction:
::indicates that a value is not required for identifying the resource- Example: no region needed for IAM resources
:*:represents a wildcard, meaning any or all values for that field- Useful for referencing multiple resources (such as all regions or all objects in a bucket)
IAM Users and Groups
Principals and IAM Identities
- Principal: an entity attempting to access AWS
- Can be a person, application, service, computer, or group of entities
- Access Process:
- Authentication
- The Principal authenticates against an IAM identity to prove its identity to AWS
- IAM users authenticate with long-term credentials (username/password or access keys)
- IAM roles authenticate with short-term credentials (via Amazon STS)
- Once authenticated, the Principal becomes an authenticated identity and AWS knows which policies apply
- Authorization
- The authenticated identity can perform only allowed actions
- AWS evaluates all policies attached or applicable to the identity and merges them into an effective set of permissions
- Authentication
IAM User

- IAM user: an identity with long-term credentials
- Used for humans, applications, or service accounts
- Think of it as one named entity acting as a Principal
- Account Limit:
- Maximum 5,000 IAM users per account
- For large-scale apps (e.g., millions of mobile users), individual IAM users are not practical
- Use IAM roles or identity federation instead
IAM Group

- IAM group: a container for IAM users
- Simplifies policy management
- A policy attached to the group applies to all users in the group
- Updating the group policy automatically updates all its users
- Simplifies policy management
- Important Notes:
- Not a Principal → cannot log in or act independently
- Cannot be referenced in resource policies (e.g., S3 bucket policies)
- Limitations and Considerations:
- A group can contain any number of IAM users (up to the account limit of 5,000 users)
- AWS has no default all-users group; it must be created manually
- Membership limit: an IAM user can belong to up to 10 groups
- No nesting: subgroups are not supported
- Soft limit: 300 groups per account (can be increased via support)
IAM Roles
IAM Roles – Key Concepts

- IAM role: an IAM identity with short-term credentials
- Designed to be used by multiple Principals, unlike IAM users which are intended for one specific Principal
- Examples of Principals that can assume a role:
- IAM users within the same AWS account
- IAM users from other AWS accounts
- External identities (e.g., federated users, apps, services)
- Roles are assumed temporarily
- A Principal becomes the role for a limited time, borrowing its permissions
- Conceptually similar to “putting on a hat”:
- You take temporary responsibility (e.g., opening the theater as an usher)
- When finished, you return the permissions, and someone else can assume the role later
- Important:
- An IAM role is not a Principal itself
- It represents a level of access within an AWS account
- Use cases for IAM roles: Link
IAM Roles – Architecture

- IAM roles are fully valid IAM identities
- Have short-term credentials that expire quickly
- Can have identity policies attached, defining permissions
- Can be referenced as a Principal in resource policies
- Two types of policies for roles:
- Permissions Policy (Identity Policy)
- Defines the actions a Principal can perform while assuming the role
- Same type used for IAM users and groups
- Trust Policy
- Defines which identities are allowed to assume the role
- Can include:
- IAM users/services in the same AWS account
- Identities/services from other AWS accounts
- Federated external users (e.g., Facebook, Google)
- Even anonymous usage
- Permissions Policy (Identity Policy)
Process: Accessing AWS Resources with a Role
- Principal attempts to authenticate as the role via IAM
- IAM checks the trust policy to ensure the Principal is allowed to assume the role
- Request is denied if the Principal is not trusted
- Principal calls AWS Security Token Service (STS) using
sts:AssumeRole - STS generates temporary credentials if allowed
- The Principal assumes the role and becomes an authenticated identity for a limited time
- When credentials expire, the Principal must reassume the role to get new temporary credentials
- Some AWS services auto-renew STS credentials; external applications (e.g., mobile apps) may need custom auto-renewal logic
Use Cases for IAM Roles
1. Grant AWS Services Permissions

- AWS services need access rights to operate on your behalf → IAM roles provide this access
- Example: Lambda Execution Role
- Lambda functions are not identities and have no permissions by default
- The IAM role trusts Lambda and can be assumed to grant temporary permissions (e.g., writing objects to S3)
- Multiple identical Lambdas can assume the same role simultaneously
- Avoid hard-coding long-term credentials in Lambda functions
- Security risk: credentials exposed in code
- Rotating keys is cumbersome
- Multiple functions cannot use the same long-term keys simultaneously
2. Grant Additional Permissions in Extraordinary Situations

- Emergency or “break-glass” access
- IAM roles can be assumed only in emergencies
- Usage is fully logged and auditable, ensuring accountability
- Example: Help-desk staff normally have read-only access
- During emergencies (e.g., admins unavailable), they can assume a temporary role with write permissions to resolve critical issues
3. Grant AWS Access to Existing Corporate Environments

- Corporations often have large identity directories (e.g., Microsoft Active Directory)
- External identities cannot access AWS directly → IAM roles with identity federation provide access
- Process:
- Users log in with their corporate credentials via SSO
- They assume an IAM role in AWS (becoming federated identities)
- Temporary permissions are granted automatically
- Multiple users can assume the same role simultaneously, with logging to track individual actions
4. Designing Applications with Many Users

- For apps with >5000 users (e.g., mobile apps), IAM users are not practical
- Web Identity Federation: IAM roles grant temporary access to users authenticating via external identity providers (Google, Facebook, Twitter)
- Users log in with existing social accounts
- No AWS credentials are stored in the app
- Scales to millions of users efficiently
- Example: Mobile app users access DynamoDB
- Each user assumes an IAM role under the hood to access resources
5. Cross-Account Access

- Multi-account environments require frequent account switching
- AWS Console Simultaneous Sign-in enables multiple accounts/roles in the same browser without logging out

- IAM roles facilitate access across accounts within an AWS Organization
- Accounts/role history is stored in the AWS Management Console
- Avoids duplicating IAM users across multiple accounts
- Simplifies permission management
- Example: When a Principal assumes a role to upload an object to an S3 bucket, the object is owned by the bucket’s account, avoiding cross-account ownership issues
Service-Linked Roles and PassRole
Service-Linked Role
- Definition: An IAM role that is tied to a specific AWS service
- Grants a predefined set of permissions that the service needs to operate on your behalf
- Creation, modification, and deletion: Controlled by the service itself
- The AWS service automatically creates and manages the role
- You configure the role via a setup wizard
- You manually configure the role through IAM, if required by the service
- Important:
- You cannot delete a service-linked role while the service requires it
- It can only be deleted once the service no longer depends on it
- Key difference from normal IAM roles: lifecycle is service-managed
- Reference: AWS Docs – Service-Linked Roles
Example: IAM policy referencing iam:CreateServiceLinkedRole

PassRole
- Definition: Allows an IAM identity to assign an existing role (including service-linked roles) to an AWS resource, without granting the role’s permissions to that identity
- Key Concept – Role Separation:
- Identity performing
iam:PassRoledoes not need:- Permissions of the role being passed
- Permissions to create, edit, or delete the role
- Identity performing
- Example Scenario:

- Bob cannot create EC2 instances directly
- Bob is allowed to perform
iam:PassRolein CloudFormation - Bob executes a CloudFormation stack that creates EC2 instances using a pre-existing service-linked role
- Bob cannot:
- Create EC2 instances manually
- Modify or delete the service-linked role
- Create new service-linked roles