Amazon EC2 API Guide
Amazon EC2 provides a web API for managing virtual machines and related resources in an AWS account. Applications can find instances, check their health, start and stop them, manage tags, inspect network access, and create storage snapshots. This guide links to 14 complete examples using signed Chilkat.Rest calls.
Choose a language to update all 14 example links below. Each link opens the complete example in that language. The guide text stays the same.
Before making requests
The examples require Chilkat 11.6.0 or later and an unlocked library. They can run outside EC2 wherever the application can reach AWS and securely hold its authorized credentials. Select the AWS account and region deliberately. These are management API requests; they do not log in to the guest operating system or execute shell commands.
Each example reads a private qa_data/aws/ec2.json file with string fields access_key and secret_key. Temporary IAM/STS credentials also require session_token. Prefer short-lived role credentials and grant only the IAM actions and resource access needed by the application. The examples read this named file explicitly; they do not discover AWS profiles, obtain role credentials, or refresh them automatically. Replace expired credentials before continuing. Keep credentials out of public web content and source control. See EC2 authentication parameters.
How a signed EC2 request maps to Chilkat
EC2 uses the Query API: an Action parameter chooses the operation, and the response is XML. The examples use HTTPS GET with Version=2016-11-15, the current EC2 API identifier. That date is an API version, not an indication that the examples are obsolete. AWS also supports POST for Query requests. See EC2 Query requests.
| Requirement | Chilkat implementation |
|---|---|
| Regional endpoint | Build ec2.{region}.amazonaws.com and use the same region for signing. Other AWS partitions have different endpoint suffixes. |
| AWS Signature Version 4 | Set AuthAws.AccessKey, SecretKey, Region, ServiceName = "ec2", and SignatureVersion = 4; attach it with Rest.SetAuthAws. |
| Operation and inputs | Use Rest.AddQueryParam for Action, Version, and operation parameters. It URL-encodes values; do not pre-encode them. |
| Temporary credentials | Add X-Amz-Security-Token to the signed query. Because these examples put the token in the query, keep request URLs and detailed diagnostics private. |
| Verified HTTPS connection | Enable Socket.RequireSslCertVerify, connect on port 443 with TLS, and pass the connection to Rest.UseConnection. |
| Send and parse | Call Rest.FullRequestNoBody("GET", "/"). Check transport completion and ResponseStatusCode separately, then use Xml with Strict = true and verify the expected response fields. |
Keep instance, AMI, volume, snapshot, security-group, and VPC IDs as strings, together with their account and region. Tags such as Name are useful for discovery but are not unique identifiers. Chilkat XML tag paths use | between child elements; they are not XPath expressions.
dryRun = true, an authorized permission check returns the DryRunOperation error; the examples recognize it as a successful check. UnauthorizedOperation is a failure. Set dryRun to false deliberately to perform the operation. A dry run does not reserve capacity or guarantee that a later live request will succeed. The snapshot example can resume read-only checks for an already recorded snapshot even when dryRun remains true.Instance Discovery and Health
Start with Find Instances by Tag and State to obtain the IDs and addresses you need. The example combines a Name-tag filter with a running-state filter and processes every matching instance, including multiple instances within one reservation. It does not assume the first result is the intended resource. Private instances may have no public address.
The listing examples follow nextToken until it is absent or empty, even after an empty page. They replace the previous request's NextToken and detect repeated tokens. The 1000-page limit is a demonstration bound: reaching it reports incomplete results. Pagination is not a snapshot of an unchanging account. See DescribeInstances.
State and health answer different questions. Running is a lifecycle state. System health concerns AWS infrastructure; instance health concerns the guest. The health example also displays attached-EBS, application, and performance summaries when returned, plus scheduled maintenance events. Missing status fields are not interpreted as healthy.
IncludeAllInstances=true includes non-running instances; it does not override explicit instance-ID filters. The regional health listing uses pagination. For a targeted check, the wait example supplies one ID and omits MaxResults, which cannot be combined with explicit IDs. It waits for running with both system and instance checks reporting ok, or for stopped when that goal is selected. Application readiness still needs its own check. See DescribeInstanceStatus.
The waiter makes at most 60 reads, with delays increasing from two to ten seconds. Network timeouts add to elapsed time. A polling limit means completion is unconfirmed. EC2 changes are eventually consistent: a newly created instance can briefly appear absent. Bounded retries handle that case; persistent absence still requires checking the account, region, and ID. See EC2 eventual consistency.
Launch, Start, Stop, and Reboot
Launch creates an instance; start resumes an existing stopped instance. Before launching, choose a suitable AMI, instance type, subnet, security group, and key pair. The AMI example searches your own images by default; set the owner to a trusted publisher when appropriate. Review architecture, creation date, deprecation, and OS suitability rather than trusting a familiar image name or taking the first result. AMI IDs are regional. See DescribeImages.
The launch example requires IMDSv2 and uses explicit network settings. Public addressing follows the selected subnet's configuration. It saves the parameters and a generated client token in ec2-launch-request.json before sending, then records the returned instance ID. Later runs load that saved request; editing source constants does not change an existing saved request. Use a separate private file for each intended launch and serialize access.
After an uncertain launch response, retain the token and exact parameters. A deliberate retry belongs to the same account, region, and subnet; changing the region or Availability Zone can create another instance. The saved ID prevents this example from submitting a recorded launch again. See AWS client-token and idempotency rules.
| Operation | Effect and completion check |
|---|---|
| Launch | Creates a billable instance. The returned ID and pending state indicate acceptance; wait for running and health checks before use. |
| Start | Starts a stopped EBS-backed instance and resumes instance usage charges. Its automatically assigned public IPv4 address can change after stop/start. |
| Stop | Requests a graceful OS shutdown. RAM and instance-store data are lost; EBS data and storage charges remain. Wait for stopped. |
| Reboot | Queues an asynchronous reboot. A successful response has return=true; it does not prove that the OS or application has recovered. |
The stop example leaves Force, Hibernate, and SkipOsShutdown at their default false values. Hibernation requires prior enablement and eligibility. Forced stopping or bypassing OS shutdown is a separate troubleshooting decision with data-integrity implications. See StopInstances and RebootInstances.
Tags and Network Access
The tagging example adds or updates Name and Environment on one resource. Existing values for those keys are replaced; unrelated tags remain. An empty value retains the key rather than deleting it. Tags can drive discovery and access policies, so choose values deliberately and keep secrets out of them. See CreateTags.
The security-group example is read-only. It displays inbound and outbound rules for a selected VPC, including IPv4/IPv6 ranges, referenced groups, and prefix lists. Protocol -1 means all protocols. For ICMP, the displayed fields represent type and code rather than TCP/UDP ports. Security groups are stateful allow rules; routes, network ACLs, and guest firewalls also affect connectivity. See DescribeSecurityGroups.
Storage and Backups
The EBS inventory includes unattached volumes, encryption, capacity, state, and every reported attachment. An attached volume is not necessarily mounted in the guest. The API's requested device name can differ from the device name seen by the OS, and Multi-Attach volumes can have more than one attachment. Unattached EBS volumes still incur storage charges. See DescribeVolumes.
The snapshot example creates a billable single-volume backup and monitors it until completed or error. Coordinate application writes and flush buffers before creation: a snapshot does not include data still cached in memory. AWS recommends stopping the instance before snapshotting its root volume. This example does not coordinate a multi-volume application backup. See CreateSnapshot.
A private ec2-snapshot-request.json checkpoint records the region, volume, and request time before creation, then the returned snapshot ID. If an ID is already recorded, rerunning resumes status reads. If a previous create was attempted but no ID was saved, the example stops for reconciliation instead of creating another snapshot: CreateSnapshot has no client-token parameter. Keep the checkpoint after a timeout. The bounded polling loop reports unconfirmed completion if its attempt limit is reached. See DescribeSnapshots.
Troubleshooting
Console output can help diagnose boot failures. The example reads the API's base64 output, decodes it, and saves the original bytes to a new private file. Check the returned timestamp: output can be delayed, missing, or empty. It is not an interactive shell or a live log stream. Avoid logging console contents indiscriminately because they can contain sensitive data. See GetConsoleOutput.
For API failures, distinguish a transport failure from an HTTP error response. EC2 errors use Errors/Error/Code and RequestID; successful responses use requestId. Record the request ID when investigating a failure. Check permissions for authorization errors, replace expired credentials, and use bounded backoff for throttled reads. A write timeout can leave its outcome uncertain, so inspect the saved request and AWS state before retrying. In particular, do not blindly repeat a reboot or snapshot creation.
Instance Termination
The termination example targets one explicit string ID, respects termination protection, and reports the returned state transition. Shutting-down means the request was accepted, not completed. Confirm terminated with DescribeInstances; an immediate not-found error alone is not proof of termination. Recently terminated instances can remain visible temporarily. Multi-instance requests across Availability Zones can partially succeed when termination protection applies, so do not assume all-or-nothing behavior. See TerminateInstances.