Iam role
- create role using aws cli
aws iam create-role `
--role-name demo-ec2 `
--assume-role-policy-document file://Trust-Policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sts:AssumeRole"
],
"Principal": {
"Service": [
"ec2.amazonaws.com"
]
}
}
]
}
attach policy to the role
aws iam attach-role-policy `
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess `
--role-name demo-ec2
create policy using aws cli
aws iam create-policy `
--policy-name s3-limited-access `
--policy-document file://policy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "s3limited",
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject"
],
"Resource": "arn:aws:s3:::*/*",
"Condition": {
"IpAddress": {
"aws:SourceIp": "183.82.2.131"
}
}
}
]
}
aws iam attach-role-policy `
--policy-arn arn:aws:iam::998850986822:policy/s3-limited-access `
--role-name demo-ec2
AWS IAM Policy Conditions
IAM policies use the Condition element to control when a policy statement applies. Conditions rely on operators (like StringEquals, IpAddress, etc.) and context keys (global or service-specific).
Condition Operators
| Operator |
Usage |
Example |
| StringEquals |
Matches exact string |
"Condition": {"StringEquals": {"aws:username": "john"}} |
| StringEqualsIgnoreCase |
Case-insensitive match |
"Condition": {"StringEqualsIgnoreCase": {"aws:username": "john"}} |
| IpAddress |
Restrict by IP range |
"Condition": {"IpAddress": {"aws:SourceIp": "203.0.113.0/24"}} |
| DateGreaterThan |
Allow after a date |
"Condition": {"DateGreaterThan": {"aws:CurrentTime": "2026-07-01T00:00:00Z"}} |
| Bool |
Boolean check |
"Condition": {"Bool": {"aws:SecureTransport": "true"}} |
| NumericLessThan |
Numeric comparison |
"Condition": {"NumericLessThan": {"s3:max-keys": "10"}} |
Global Context Keys
| Key |
Purpose |
Example |
| aws:SourceIp |
Restrict by IP |
"Condition": {"IpAddress": {"aws:SourceIp": "192.0.2.0/24"}} |
| aws:CurrentTime |
Time-based access |
"Condition": {"DateLessThan": {"aws:CurrentTime": "2026-07-31T23:59:59Z"}} |
| aws:SecureTransport |
Require HTTPS |
"Condition": {"Bool": {"aws:SecureTransport": "true"}} |
| aws:RequestTag |
Check request tags |
"Condition": {"StringEquals": {"aws:RequestTag/Project": "Alpha"}} |
| aws:ResourceTag |
Match resource tags |
"Condition": {"StringEquals": {"aws:ResourceTag/Environment": "Prod"}} |
Service-Specific Context Keys
EC2 Instance Type
"Condition": {
"StringEquals": { "ec2:InstanceType": "t2.micro" }
}