AWS CLI v2 Python Wrapper
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
- breaking Python 3.6 support was removed in version 2.0.0. Projects using older Python versions must upgrade to Python 3.7 or newer to use awscliv2 >= 2.0.0.
- gotcha This library is an unofficial wrapper for the AWS CLI v2, not an official AWS SDK or an official AWS-published PyPI package. Users should be aware of this distinction and verify its suitability for their security requirements.
- gotcha By default, the library uses the `amazon/aws-cli` Docker image to run AWS CLI commands if the native AWS CLI v2 binary is not installed via `awsv2 --install`. Using Docker may involve running as a root user and could require manual permission adjustments for downloaded files.
- gotcha In versions prior to 2.3.1, `AWSAPI.execute` would raise an exception on a non-zero status code, and specific issues existed with output handling on Windows and `AWSAPI.assume_role` parsing. While fixed in 2.3.1, users on older versions may encounter these issues.
Install
-
pip install awscliv2 -
awsv2 --install
Imports
- AWSAPI
from awscliv2.api import AWSAPI
- AWSCLIError
from awscliv2.exceptions import AWSCLIError
Quickstart
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}")