Lesson 1 of 1 Amazon EC2

Providing Credentials, Configuration and Access to Applications on EC2

This lesson explains what developers need to know about Amazon EC2: how applications on an instance get credentials, configuration and access, and how instances behave over their lifecycle. The exam rarely asks you to administer servers.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain how an instance profile and the instance metadata service provide temporary credentials.
  • Describe how user data scripts and AMIs configure instances, and where to look when user data fails.
  • Distinguish stopping an instance from terminating it.
  • Explain why Session Manager is preferred to SSH for shell access.

Credentials and instance metadata

An application running on an EC2 instance should never use stored access keys. Instead, an IAM role is attached to the instance through an instance profile. EC2 makes temporary credentials for that role available to the instance and rotates them automatically, and the AWS SDKs and CLI find and refresh them without any code.

The credentials are served by the instance metadata service (IMDS), an HTTP endpoint at http://169.254.169.254 that is reachable only from inside the instance. Besides credentials, it provides information about the instance, such as its ID, type, Availability Zone and Region, which code can use to configure itself.

Instances should require IMDSv2. With IMDSv2, a caller must first obtain a session token with an HTTP PUT request and then present it with each metadata request. This protects against server-side request forgery (SSRF), in which an attacker tricks a vulnerable web application into requesting a URL on the attacker's behalf: such attacks can usually make only GET requests, so they cannot obtain the token and therefore cannot steal the role's credentials. Current SDKs use IMDSv2 automatically.

TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/placement/region
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/

The following diagram shows the two IMDSv2 requests from the example above and why they block SSRF.

Role credentials on EC2 through IMDSv2. The application first sends an HTTP PUT to the instance metadata service at 169.254.169.254 for a session token, then presents the token with each GET, for example to fetch the instance profile's temporary credentials, which EC2 rotates automatically. An SSRF attack that can only make GET requests cannot obtain the token.
Current SDKs use IMDSv2 automatically, so application code never handles the token.

User data and AMIs

User data scripts run as root at first boot (by default only once) to install and configure software. Output goes to /var/log/cloud-init-output.log, the first place to look when an instance does not come up as expected.

#!/bin/bash
dnf install -y python3.12
aws s3 cp s3://deploy-artifacts/orders-api.tar.gz /opt/ && tar -xzf /opt/orders-api.tar.gz -C /opt
systemctl enable --now orders-api

Long scripts slow start-up, so bake software every instance needs into a custom AMI. For repeatable configuration, use launch templates or Systems Manager State Manager.

Stop vs terminate

Stopping and terminating an instance are different actions with different consequences. Stopping an instance backed by Amazon EBS shuts it down but keeps it: its EBS volumes and their data remain, compute charges stop while storage charges continue, and it can be started again later, usually on different hardware. Terminating an instance deletes it permanently, and its root EBS volume is deleted by default unless the volume's DeleteOnTermination setting has been changed.

Two kinds of data do not survive either action. Instance store volumes are physically attached to the host, so their data is lost when the instance stops or terminates; they suit only temporary data such as caches. A public IPv4 address assigned automatically is released when the instance stops, so it usually changes on the next start; an Elastic IP address, or a load balancer's DNS name in front of the instance, gives clients a stable address. The following table summarises the differences.

Stop (EBS-backed)
EBS volumesKept
Instance store dataLost
Public IPUsually changes, unless it has an Elastic IP
Terminate
EBS volumesRoot volume deleted by default
Instance store dataLost
Public IPReleased
Sort into groups

What survives a stop?

Exam skills 1.3.2

Decide what is kept when an EBS-backed instance is stopped and started.

Log in to try this activity Interactive activities are free with an account.

Access and monitoring

Developers sometimes need a shell on an instance to investigate a problem. SSH works with a key pair and requires port 22 to be open to the developer's address. AWS Systems Manager Session Manager is the preferred alternative: the SSM Agent on the instance connects outwards to Systems Manager, so no inbound ports or keys are needed, access is controlled with IAM, and sessions can be logged to Amazon S3 or CloudWatch Logs for audit.

EC2 publishes metrics such as CPU utilisation, network traffic and status checks to Amazon CloudWatch automatically, every five minutes by default or every minute with detailed monitoring. It cannot see inside the operating system, so it does not report memory or disk space usage. Installing the CloudWatch agent on the instance adds these metrics and can also send application log files to CloudWatch Logs. Choosing an instance type that matches the workload, for example a memory-optimised type for an in-memory cache, is easier once these metrics are available.

Scenario questions

Work with instances

Exam skills 2.1.3 · 4.1.1

Practise metadata, user data and access for EC2 instances.

Log in to try this activity Interactive activities are free with an account.
Worked example

A user data script that did nothing

An instance launches but the application from its user data script is not running. The developer investigates:

CheckFinding
/var/log/cloud-init-output.logaws s3 cp failed with "Unable to locate credentials"
Instance profileNone attached
MetadataIMDSv2 is required; the script used an outdated CLI version that supports IMDSv1 only

Attaching an instance profile with read access to the artifact bucket, and using a current CLI that supports IMDSv2 tokens, fixes it. User data runs only on first boot by default, so after fixing the script the developer launches a new instance rather than rebooting the old one.

Check yourself

How does an application on EC2 get AWS credentials without storing access keys on the instance?

Show answer

An IAM role is attached through an instance profile. The SDK gets temporary credentials from the instance metadata service and refreshes them automatically.

Exam Tips

Remember for the exam

  • Code on EC2 should get credentials from an instance profile role, never from stored access keys.
  • To find the instance's own ID or Region from code, query the instance metadata service.
  • To run setup scripts at launch, use user data; for faster start-up, bake software into a custom AMI.
  • If the public IP changes after a stop and start, use an Elastic IP address or a load balancer's DNS name.