AWS CLI v2 Python Wrapper

2.3.1 · active · verified Sun Apr 12

awscliv2 is a Python wrapper designed to provide a programmatic interface for interacting with the AWS CLI v2. It allows Python applications to execute AWS CLI commands, parse their output, and manage AWS resources without directly invoking shell commands. The library supports installing and updating the underlying AWS CLI v2 binaries or utilizing a Docker fallback. It is actively maintained, with the current version being 2.3.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `AWSAPI` client and execute a basic AWS CLI command, such as listing S3 buckets. Ensure your AWS credentials are configured either via environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`) or by running `awsv2 --configure` previously. The `AWSCLIError` is recommended for catching CLI-specific issues.

import os
from awscliv2.api import AWSAPI
from awscliv2.exceptions import AWSCLIError

# AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY should be set as environment variables
# or configured via `awsv2 --configure` for the underlying AWS CLI to pick them up.
# Example: os.environ['AWS_ACCESS_KEY_ID'] = 'YOUR_ACCESS_KEY'
# Example: os.environ['AWS_SECRET_ACCESS_KEY'] = 'YOUR_SECRET_KEY'

aws_api = AWSAPI()
try:
    # List S3 buckets
    output = aws_api.execute(['s3', 'ls'])
    print('S3 Buckets:\n', output)

    # Describe EC2 instances (example, might require specific region/permissions)
    # output = aws_api.execute(['ec2', 'describe-instances'])
    # print('EC2 Instances:\n', output)

except AWSCLIError as e:
    print(f"AWS CLI Error: {e.return_code} - {e.stderr}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →