Sample code for 30+ languages & platforms
Visual FoxPro Requires Chilkat v11.6.0+

Amazon EC2: Add or Update Resource Tags

See more Amazon EC2 Examples

Live mode changes tags. Add or replace the Name and Environment tags on one EC2 resource. Existing values for those keys are overwritten; other tags remain. Resource IDs, tag keys, and values remain strings. AddQueryParam encodes spaces and special characters without manual URL encoding.

Name is a conventional tag, not a unique identifier. Do not place secrets in tags. The aws: prefix is reserved. The usual limit is 50 user-defined tags per resource. CreateTags does not remove a tag: an empty value keeps the key with an empty value. A separate DeleteTags request is needed for removal.

Dry run by default: change dryRun to false deliberately for the live operation. DryRunOperation means the permission check passed, not that a resource was changed or that the later operation is guaranteed to succeed. The example never automatically changes a dry run into a live request.

Uses the current EC2 Query API (Version=2016-11-15) over HTTPS. Chilkat.Rest and AuthAws sign the GET request with AWS Signature Version 4, service ec2. Set the region once; the code builds the corresponding commercial AWS endpoint. Other partitions require their own endpoint suffix. EC2 returns XML, unlike DynamoDB's JSON protocol. AddQueryParam encodes parameter values.

Load current IAM credentials from a private qa_data/aws/ec2.json with string fields access_key, secret_key, and, for temporary credentials, session_token. Prefer short-lived role credentials. The example explicitly reads this file; it does not discover profiles or refresh expired credentials. The session token is included in the signed query, so keep URLs and diagnostics private. A Socket enables TLS certificate verification before handing its connection to Rest.

IAM permissions for the illustrated requests: ec2:CreateTags. Use least-privilege permissions for the intended resources; EC2 describe operations generally require Resource *.

Transport completion, HTTP status, and XML validity are checked separately. API errors contain Errors/Error/Code and RequestID; successful responses use requestId. Check the error code rather than assuming every HTTP 4xx means bad input. Use bounded exponential backoff with jitter for retryable failures. EC2 is eventually consistent: a recent resource change may not appear immediately. Verify account, region, ID, and observed state before retrying a change whose outcome is uncertain.

CreateTags reference

Chilkat Visual FoxPro Downloads

Visual FoxPro
LOCAL lnSuccess
LOCAL loCredentials
LOCAL lcRegion
LOCAL loEndpoint
LOCAL loAws
LOCAL loRest
LOCAL loConnection
LOCAL loXml
LOCAL lcResponseXml
LOCAL lcErrorCode
LOCAL lcResourceId
LOCAL lcInstanceName
LOCAL lnDryRun

*  Assumes Chilkat is unlocked. See Global Unlock Sample.
lnSuccess = 0
*  Private configuration, not a file in public web content or source control.
*  Load current IAM credentials authorized for the EC2 operation.
loCredentials = CreateObject('Chilkat.JsonObject')
loCredentials.Strict = 1
lnSuccess = loCredentials.LoadFile("qa_data/aws/ec2.json")
IF (lnSuccess <> 1) THEN
    ? "Could not load private AWS credentials."
    RELEASE loCredentials
    CANCEL
ENDIF

IF ((loCredentials.JsonTypeOf("access_key") <> 1) OR (loCredentials.StringOf("access_key") = "")) THEN
    ? "Missing or invalid access_key."
    RELEASE loCredentials
    CANCEL
ENDIF

IF ((loCredentials.JsonTypeOf("secret_key") <> 1) OR (loCredentials.StringOf("secret_key") = "")) THEN
    ? "Missing or invalid secret_key."
    RELEASE loCredentials
    CANCEL
ENDIF

*  Set this once to the region containing the instances.
lcRegion = "us-west-2"
loEndpoint = CreateObject('Chilkat.StringBuilder')
loEndpoint.Append("ec2.")
loEndpoint.Append(lcRegion)
loEndpoint.Append(".amazonaws.com")
loAws = CreateObject('Chilkat.AuthAws')
loAws.AccessKey = loCredentials.StringOf("access_key")
loAws.SecretKey = loCredentials.StringOf("secret_key")
loAws.Region = lcRegion
loAws.ServiceName = "ec2"
loAws.SignatureVersion = 4
loRest = CreateObject('Chilkat.Rest')
loRest.ConnectTimeoutMs = 20000
loRest.IdleTimeoutMs = 60000
lnSuccess = loRest.SetAuthAws(loAws)
IF (lnSuccess <> 1) THEN
    ? "Could not configure AWS signing."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    CANCEL
ENDIF

*  Temporary IAM/STS credentials require their session token on every signed request.
*  AddQueryParam includes it in SigV4's canonical query. Never log the request URL.
*  Leave session_token absent or empty only for credentials that do not have one.
IF (loCredentials.HasMember("session_token") = 1) THEN
    IF (loCredentials.JsonTypeOf("session_token") <> 1) THEN
        ? "session_token must be a string."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        CANCEL
    ENDIF

    IF (loCredentials.StringOf("session_token") <> "") THEN
        lnSuccess = loRest.AddQueryParam("X-Amz-Security-Token",loCredentials.StringOf("session_token"))
        IF (lnSuccess <> 1) THEN
            ? "Could not set the session-token parameter."
            RELEASE loCredentials
            RELEASE loEndpoint
            RELEASE loAws
            RELEASE loRest
            CANCEL
        ENDIF

    ENDIF

ENDIF

*  Supply a Socket to explicitly enable TLS certificate verification.
loConnection = CreateObject('Chilkat.Socket')
loConnection.RequireSslCertVerify = 1
loConnection.MaxReadIdleMs = 60000
loConnection.MaxSendIdleMs = 60000
lnSuccess = loConnection.Connect(loEndpoint.GetAsString(),443,1,20000)
IF (lnSuccess <> 1) THEN
    ? "TLS connection failed; inspect diagnostics privately."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    CANCEL
ENDIF

lnSuccess = loRest.UseConnection(loConnection,1)
IF (lnSuccess <> 1) THEN
    ? "Could not attach the TLS connection."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    CANCEL
ENDIF

*  EC2 uses the Query API and XML responses, not AWS JSON protocol headers.
*  AddQueryParam URL-encodes the values; do not pre-encode IDs or tokens.
loXml = CreateObject('Chilkat.Xml')
loXml.Strict = 1
lnSuccess = loRest.AddQueryParam("Version","2016-11-15")
IF (lnSuccess <> 1) THEN
    ? "Could not set Version."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lcResponseXml = ""
lcErrorCode = ""
lcResourceId = "i-1234567890abcdef0"
lcInstanceName = "example-instance"
lnDryRun = 1
lnSuccess = loRest.AddQueryParam("Action","CreateTags")
IF (lnSuccess <> 1) THEN
    ? "Could not set Action."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("ResourceId.1",lcResourceId)
IF (lnSuccess <> 1) THEN
    ? "Could not set ResourceId.1."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("Tag.1.Key","Name")
IF (lnSuccess <> 1) THEN
    ? "Could not set Tag.1.Key."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("Tag.1.Value",lcInstanceName)
IF (lnSuccess <> 1) THEN
    ? "Could not set Tag.1.Value."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("Tag.2.Key","Environment")
IF (lnSuccess <> 1) THEN
    ? "Could not set Tag.2.Key."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loRest.AddQueryParam("Tag.2.Value","test")
IF (lnSuccess <> 1) THEN
    ? "Could not set Tag.2.Value."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

IF (lnDryRun = 1) THEN
    lnSuccess = loRest.AddQueryParam("DryRun","true")
    IF (lnSuccess <> 1) THEN
        ? "Could not set DryRun."
        RELEASE loCredentials
        RELEASE loEndpoint
        RELEASE loAws
        RELEASE loRest
        RELEASE loConnection
        RELEASE loXml
        CANCEL
    ENDIF

ENDIF

lcResponseXml = loRest.FullRequestNoBody("GET","/")
IF (loRest.LastMethodSuccess <> 1) THEN
    ? "Request did not complete; inspect diagnostics privately."
    *  The operation might already have been accepted. Check state before retrying.
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

lnSuccess = loXml.LoadXml(lcResponseXml)
IF (loRest.ResponseStatusCode <> 200) THEN
    ? "EC2 HTTP status: " + STR(loRest.ResponseStatusCode)
    IF (lnSuccess = 1) THEN
        IF (loXml.HasChildWithTag("Errors|Error|Code") = 1) THEN
            lcErrorCode = loXml.GetChildContent("Errors|Error|Code")
            IF ((lnDryRun = 1) AND (lcErrorCode = "DryRunOperation")) THEN
                ? "Dry run authorized. No resource was changed."
                ? "Set dryRun to false only when ready to perform the operation."
                RELEASE loCredentials
                RELEASE loEndpoint
                RELEASE loAws
                RELEASE loRest
                RELEASE loConnection
                RELEASE loXml
                CANCEL
            ENDIF

            ? "AWS error code: " + lcErrorCode
        ENDIF

        IF (loXml.HasChildWithTag("RequestID") = 1) THEN
            ? "AWS request ID: " + loXml.GetChildContent("RequestID")
        ENDIF

    ENDIF

    *  Keep full error messages and signed request diagnostics private.
    *  UnauthorizedOperation is not a successful dry run. Check IAM permissions.
    *  Retry throttled reads with bounded backoff; renew expired credentials.
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

IF (lnSuccess <> 1) THEN
    ? "Expected a well-formed XML response."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

IF (loXml.Tag <> "CreateTagsResponse") THEN
    ? "Unexpected EC2 response element."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

IF (lnDryRun = 1) THEN
    ? "Unexpected HTTP 200 for a dry run; do not treat this as authorization to proceed."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

IF ((loXml.HasChildWithTag("requestId") <> 1) OR (loXml.GetChildContent("requestId") = "")) THEN
    ? "Missing or empty requestId."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

? "AWS request ID: " + loXml.GetChildContent("requestId")
IF ((loXml.HasChildWithTag("return") <> 1) OR (loXml.GetChildContent("return") = "")) THEN
    ? "Missing or empty return."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

IF (loXml.GetChildContent("return") <> "true") THEN
    ? "Tag update was not acknowledged."
    RELEASE loCredentials
    RELEASE loEndpoint
    RELEASE loAws
    RELEASE loRest
    RELEASE loConnection
    RELEASE loXml
    CANCEL
ENDIF

? "Specified tags added or updated; other tags were retained."

RELEASE loCredentials
RELEASE loEndpoint
RELEASE loAws
RELEASE loRest
RELEASE loConnection
RELEASE loXml