Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Managing EC2, IAM and VPC with Python

Practical guide to managing Amazon EC2 instances, IAM identities and VPC networks from Python using boto3, with definitions, exact API call order, example code traces and exam-style notes.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Managing compute, identity and networking is core to any cloud application. Engineers use EC2 for virtual servers, IAM for secure access control, and VPC for private network design; automating these with Python and boto3 lets you reproducibly create, configure and tear down environments for development, testing and production.

Key ideas

  • VPC (Virtual Private Cloud) — a logically isolated virtual network. Define: a subnet is a CIDR block inside a VPC; a route table defines how traffic leaves subnets; an internet gateway (IGW) enables Internet access (IPv4 and IPv6) for public subnets. Assumption: to make an instance public, the subnet must have a route to an IGW, the instance must have a public IP, and the security group must allow the required inbound traffic (e.g., TCP 22 for SSH).

  • boto3 — the AWS SDK for Python. Two primary interfaces: client (low-level service API, returns dictionaries) and resource (higher-level, object-oriented wrappers). Exact rule: use clients for APIs not exposed as resources and resources for simpler object operations. Example: ec2_client = boto3.client('ec2'), ec2_resource = boto3.resource('ec2').

  • Dependency order and invariants when building an environment:

    1. Create VPC → create subnet(s) → create and attach IGW → create route table and add route 0.0.0.0/0 to IGW → associate route table with public subnet → enable public IP auto-assign on subnet (or set on instance). This order ensures public subnets can reach the Internet. If you need public DNS hostnames, also enable DNS hostnames on the VPC.
    2. Create IAM role (with trust policy for the service, e.g., ec2.amazonaws.com) → attach policies to role → create instance profile (for EC2) → attach role via instance profile when launching instance. Without an instance profile, EC2 cannot assume the role.
    3. Create Security Group(s) and add inbound/outbound rules before or after launch; rules take effect immediately.
  • Security rules: security groups are stateful; network ACLs are stateless. Draw to show difference: draw VPC rectangle, subnets inside, a security group attached to instance with arrows showing inbound rule and automatic return flow (stateful). Label network ACLs as separate list-ordered rules applied at subnet boundary.

Formulas

(For a programming topic, list syntax lines to remember.) import boto3 — import AWS SDK for Python. ec2_client = boto3.client('ec2', region_name='ap-south-1') — low-level EC2 client in a region. ec2_resource = boto3.resource('ec2', region_name='ap-south-1') — high-level EC2 resource. ec2_resource.create_instances(ImageId='ami-...', InstanceType='t2.micro', KeyName='mykey', MinCount=1, MaxCount=1, NetworkInterfaces=[...]) — create EC2 instances. iam_client.create_role(RoleName='MyRole', AssumeRolePolicyDocument=json.dumps(trust_policy)) — create an IAM role with trust policy. iam_client.attach_role_policy(RoleName='MyRole', PolicyArn='arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess') — attach managed policy. ec2_client.create_vpc(CidrBlock='10.0.0.0/16') — create a VPC. ec2_client.create_subnet(VpcId=vpc_id, CidrBlock='10.0.1.0/24') — create subnet. ec2_client.create_internet_gateway() and ec2_client.attach_internet_gateway(InternetGatewayId=igw_id, VpcId=vpc_id) — create and attach IGW. ec2_client.create_route(RouteTableId=rtb_id, DestinationCidrBlock='0.0.0.0/0', GatewayId=igw_id) — add default route to IGW. ec2_client.authorize_security_group_ingress(GroupId=sg_id, IpProtocol='tcp', FromPort=22, ToPort=22, CidrIp='203.0.113.0/24') — add ingress rule.

Worked examples

Example 1 — Launching a public EC2 instance with an IAM role (step-by-step trace): Inputs: region ap-south-1, AMI ami-0123456789abcdef0, instance type t3.micro, key pair mykey, CIDR blocks as below. Steps:

  1. Create VPC: vpc = ec2_client.create_vpc(CidrBlock='10.0.0.0/16') → suppose VpcId = vpc-aaa111.
  2. Create subnet: subnet = ec2_client.create_subnet(VpcId='vpc-aaa111', CidrBlock='10.0.1.0/24') → SubnetId = subnet-bbb222.
  3. Create and attach IGW: igw = ec2_client.create_internet_gateway() → igw-ccc333; then attach_internet_gateway(InternetGatewayId='igw-ccc333', VpcId='vpc-aaa111').
  4. Create route table and default route: rtb = ec2_client.create_route_table(VpcId='vpc-aaa111') → rtb-ddd444; create_route(RouteTableId='rtb-ddd444', DestinationCidrBlock='0.0.0.0/0', GatewayId='igw-ccc333').
  5. Associate route table: associate_route_table(RouteTableId='rtb-ddd444', SubnetId='subnet-bbb222').
  6. Enable public IP auto-assign on subnet (or set AssociatePublicIpAddress on instance network interface): modify_subnet_attribute(SubnetId='subnet-bbb222', MapPublicIpOnLaunch={'Value': True}).
  7. Create Security Group in VPC: create_security_group(VpcId='vpc-aaa111', GroupName='ssh-sg', Description='allow ssh') → sg-eee555.
  8. Add ingress rule for SSH (restrict source to your IP): authorize_security_group_ingress(GroupId='sg-eee555', IpProtocol='tcp', FromPort=22, ToPort=22, CidrIp='203.0.113.0/32').
  9. Create IAM role for EC2: trust policy = {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]} → create_role(RoleName='ec2-role', AssumeRolePolicyDocument=json.dumps(trust_policy)).
  10. Create instance profile and add role: create_instance_profile(InstanceProfileName='ec2-profile'), add_role_to_instance_profile(InstanceProfileName='ec2-profile', RoleName='ec2-role').
  11. Launch EC2 with instance profile: use IamInstanceProfile={'Name': 'ec2-profile'} and NetworkInterfaces=[{'SubnetId':'subnet-bbb222','DeviceIndex':0,'AssociatePublicIpAddress':True,'Groups':['sg-eee555']}] in run_instances. Result: An instance i-fff666 appears with a public IP and the IAM role attached. Answer to inspect: check console or describe_instances(InstanceIds=['i-fff666']) to confirm PublicIpAddress and IamInstanceProfile.

Example 2 — Creating an IAM role mistake trace and fix: Problem: EC2 shows no role in console after launch. Likely reasons:

  • You created a role but forgot to create an instance profile and add the role to it (fix: create_instance_profile + add_role_to_instance_profile).
  • You attached the instance profile after launch (fix: you can attach an IAM role to a running EC2 instance using the AssociateIamInstanceProfile API or aws ec2 associate-iam-instance-profile CLI; no stop is required. To change an attached role/profile, use ReplaceIamInstanceProfileAssociation). Note: allow for eventual consistency after creating the instance profile/role.

Example 3 — Small program that lists EC2 instances in a VPC (algorithm trace): Code outline: ec2 = boto3.client('ec2') resp = ec2.describe_instances(Filters=[{'Name':'vpc-id','Values':['vpc-aaa111']}]) Trace: API returns Reservations array; iterate reservations then instances; for each instance print InstanceId, State.Name, PublicIpAddress if present.

Common mistakes

  • Not creating or attaching an instance profile for EC2 roles; creating a role alone is not sufficient.
  • Opening security group to 0.0.0.0/0 for SSH in exam answers; exam expects mention of restricting to admin IPs.
  • Expecting public IP just because instance is in a VPC; you must ensure subnet route to IGW and public IP assignment.
  • Confusing security group (stateful) with network ACL (stateless) and expecting return packets blocked.
  • Not JSON-encoding the trust policy when calling create_role; passing a Python dict instead of a string causes an error.

For your exam

Question types you will get:

  • Definitions: define EC2 instance, IAM role, VPC, security group.
  • Short notes: steps to launch an EC2 instance with an IAM role using boto3; security differences between SG and NACL.
  • Derivations/sequence: show the correct order of API calls to make a subnet public (VPC → subnet → IGW → route table → associate → launch instance).
  • Programs: write a short Python/boto3 function to create a VPC and a public subnet, or to attach an IAM role to an instance.
  • Diagrams: draw a VPC rectangle with a public subnet, IGW outside, route table arrow for 0.0.0.0/0, and an EC2 instance with a security group. What full-marks answers include:
  • Precise definitions with bold terms, the exact API call order and required parameters, sample JSON for trust policies, and security considerations (limit SSH CIDR, avoid hard-coded AWS credentials in code). Include one-liner boto3 syntax demonstrating the core action.

Quick check

  1. What JSON key must a role's trust policy include to allow EC2 to assume it?
  2. Which boto3 interface returns higher-level objects: client or resource?
  3. Name two things required to make an EC2 instance reachable from the Internet. Answers: 1) "Principal": {"Service": "ec2.amazonaws.com"} in the Statement (assume-role policy). 2) resource. 3) a route to an Internet Gateway (0.0.0.0/0 → IGW) and a public IP assigned to the instance (or Elastic IP) plus appropriate security group rules.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?