Back to results for “Resources”
AWS › AWS CLI & SDKs

How do you build robust, idempotent automation scripts using the AWS CLI or SDKs that can safely be run multiple times without causing errors or duplicate resources?

Advanced

Answer

Building idempotent automation involves checking whether a resource already exists before attempting to create it, using conditional logic based on the API's own responses, leveraging built in idempotency tokens that many AWS APIs support to safely retry a request without creating duplicate resources, and designing scripts to gracefully handle already exists errors as a successful outcome rather than treating them as failures, ensuring the same script can be safely rerun during a failed deployment recovery without unwanted side effects.
import boto3
client = boto3.client('ec2')
try:
    client.create_key_pair(KeyName='my-key')
except client.exceptions.ClientError as e:
    if 'InvalidKeyPair.Duplicate' not in str(e):
        raise
Real-world example A deployment automation script checks whether an S3 bucket already exists before attempting to create it, allowing the exact same script to be safely rerun after a partial failure without throwing an unnecessary error about the bucket already existing.

Common follow-ups: What is an idempotency token and which AWS APIs commonly support them?;How do infrastructure as code tools like CloudFormation handle idempotency differently than custom scripts?