mkdevs

[ TWITTER ] [ FACEBOOK ] [ GITHUB ] [ LINKEDIN ]

Bienvenue sur mkdevs



📒 AWS - Local - Créer un bucket et l'utiliser

On va ici utiliser le boilerplate décrit ici afin de se former ou de rafraichir la mémoire sur le travail sur AWS mais en local, ainsi pas de coup additionnel à prévoir.

On va écrire un script Python simple pour interagir avec notre cloud virtuel. On va configurer notre script Python pour qu'il se connecte à notre Amazon S3 (MiniStack).

Normalement, Python se connecte à Internet pour communiquer avec Amazon. Mais on utilise une option appelée endpoint_url pour forcer Python à communiquer avec notre Ministack, qui effectue les tests en local.

# This is Python code. Boto3 is the official library that talks to AWS.
import boto3

# All clients use the same endpoint
# We tell Boto3 to talk to our awslocal container port 4566 instead of the real internet.
# We use fake passwords ('test', 'test') because Ministack doesn't care ! (defined in .env file too)
def client(service):
    return boto3.client(
        service,
        endpoint_url="http://awslocal:4566",
        aws_access_key_id="test",
        aws_secret_access_key="test",
        region_name="us-east-1",
    )

# S3
s3 = client("s3")
# Test 01. We create a new bucket called my-bucket
s3.create_bucket(Bucket="my-bucket")
# Test 02. We create a new object in bucket called hello.txt
s3.put_object(Bucket="my-bucket", Key="hello.txt", Body=b"Hello, MiniStack!")
# Test 03. We read content of previously created object and print in console
obj = s3.get_object(Bucket="my-bucket", Key="hello.txt")
print(obj["Body"].read())  # b'Hello, MiniStack!'