AWS KMS: Retarget a Key Alias
See more AWS KMS Examples
Uses the current AWS KMS API. Configure the region and keep credentials in private qa_data/aws/kms.json, with nonempty string fields access_key and secret_key. The examples do not obtain or refresh credentials. Keep diagnostics private; they may contain credentials or sensitive key data. Create the output directory before running file-writing examples.
Uses the AWS JSON 1.1 protocol with TrentService targets, service kms, HTTPS certificate verification, and Signature Version 4. When using temporary credentials, also provide a nonempty session_token; this Rest example includes it in the signed query on each request. Never log that URL. The endpoint shown is for the commercial AWS partition; use the appropriate endpoint for other partitions. Failures stop the sample; production retry policies should use bounded backoff with jitter and reconcile uncertain writes.
Where a key is required, set string key_id to its fixed key ARN in the configured region. Additional named fields and input files are described below. Keep output files private when they contain plaintext or policies. The code does not automatically retry mutations, refresh credentials, or create output directories. A successful request can precede propagation of a state change. Discard sensitive objects promptly; clearing one buffer does not erase copies held in strings, JSON, or runtime memory.
Uses alias/chilkat-example in the selected account and region. The target must be an eligible key in the same account and region. Retargeting an alias affects future alias-based operations; UpdateAlias requires compatible key type and usage and permissions on both old and new keys.
API actions used: kms:UpdateAlias. IAM permissions and key policies must allow the actual resources; grant and multi-Region workflows can need permissions in more than one region/account.
Chilkat Python Downloads
import sys
import chilkat2
success = False
stringCompare = chilkat2.StringBuilder()
# Assumes Chilkat is unlocked. See Global Unlock Sample.
# Keep this credentials file outside public web content and source control.
credentials = chilkat2.JsonObject()
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/kms.json")
if (success != True):
print("Could not load private KMS configuration.")
sys.exit()
stringCompare.SetString(credentials.StringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == True)):
print("Missing or invalid access_key.")
sys.exit()
stringCompare.SetString(credentials.StringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == True)):
print("Missing or invalid secret_key.")
sys.exit()
region = "us-west-2"
endpoint = chilkat2.StringBuilder()
endpoint.Append("kms.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = chilkat2.AuthAws()
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "kms"
aws.SignatureVersion = 4
rest = chilkat2.Rest()
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
success = rest.SetAuthAws(aws)
if (success != True):
print("Could not configure AWS signing.")
sys.exit()
if (credentials.HasMember("session_token") == True):
stringCompare.SetString(credentials.StringOf("session_token"))
stringMatch3 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch3 == True)):
print("Missing or invalid session_token.")
sys.exit()
connection = chilkat2.Socket()
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
if (success != True):
print("TLS connection failed; inspect diagnostics privately.")
sys.exit()
success = rest.UseConnection(connection,True)
if (success != True):
print("Could not attach TLS connection.")
sys.exit()
# Keep connection alive while Rest uses it.
body = chilkat2.JsonObject()
result = chilkat2.JsonObject()
result.Strict = True
stringCompare.SetString(credentials.StringOf("key_id"))
stringMatch4 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("key_id") != 1) or (stringMatch4 == True)):
print("Missing or invalid key_id.")
sys.exit()
keyId = credentials.StringOf("key_id")
# Choose the intended customer alias. Do not use the reserved alias/aws/ prefix.
aliasName = "alias/chilkat-example"
body.Clear()
success = body.UpdateString("AliasName",aliasName)
if (success != True):
print("Could not set AliasName.")
sys.exit()
success = body.UpdateString("TargetKeyId",keyId)
if (success != True):
print("Could not set TargetKeyId.")
sys.exit()
success = rest.ClearAllQueryParams()
if (success != True):
print("Could not clear previous query parameters.")
sys.exit()
# Keep the JSON operation body separate from authentication parameters.
# Include STS credentials in the signed query; never log the request URL.
if (credentials.HasMember("session_token") == True):
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
if (success != True):
print("Could not set session token.")
sys.exit()
success = rest.AddHeader("X-Amz-Target","TrentService.UpdateAlias")
if (success != True):
print("Could not set operation.")
sys.exit()
success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
if (success != True):
print("Could not set content type.")
sys.exit()
responseJson = rest.FullRequestString("POST","/",body.Emit())
if (rest.LastMethodSuccess != True):
print("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.")
sys.exit()
if (rest.ResponseStatusCode != 200):
print("KMS HTTP status: " + str(rest.ResponseStatusCode))
success = result.Load(responseJson)
if (success == True):
if (result.JsonTypeOf("__type") == 1):
print("AWS error code: " + result.StringOf("__type"))
print("AWS request ID: " + rest.ResponseHdrByName("x-amzn-RequestId"))
# Do not print full bodies, headers, credentials, key material, or tokens.
sys.exit()
print("Alias request accepted.")