メインコンテンツまでスキップ

AWS S3の作成から公開まで

AWS S3を作成し、Web公開するまでの手順を解説します。
※ 操作はすべてAWS Python ライブラリ(boto3)を使用して実施します。

以降の内容は以下の記事を前提とします

ロールへの権限付与

必要な権限をロールに付与します。

import boto3
from botocore.exceptions import ClientError

# Configuration constants
PROFILE_NAME = 'resources_dev_admin'
ROLE_NAME = 'ResourcesEnvMainRole'

# List of IAM policies to attach
POLICY_ARNS = [
'arn:aws:iam::aws:policy/AmazonS3FullAccess'
]

# Initialize AWS session and IAM client
session = boto3.Session(profile_name=PROFILE_NAME)
iam_client = session.client('iam')

print(f"Starting to attach policies to role '{ROLE_NAME}' using profile '{PROFILE_NAME}'...")

# Loop through each policy and attach it to the role
for policy_arn in POLICY_ARNS:
try:
iam_client.attach_role_policy(
RoleName=ROLE_NAME,
PolicyArn=policy_arn
)
print(f"Success: Attached {policy_arn.split('/')[-1]}.")
except ClientError as e:
print(f"Error: Failed to attach {policy_arn.split('/')[-1]}.")
print(e.response['Error']['Message'])

print("Process completed.")

S3の作成及びWeb公開

import json
import boto3

# 1. Initialize AWS session using the specific profile
session = boto3.Session(profile_name='resources_dev')
region_name = session.region_name

# Initialize S3 client with the profile's default region
s3_client = session.client('s3', region_name=region_name)
bucket_name = 'bucket-test-20260813-dev0813'

# 2. Create S3 bucket using the detected region config
s3_client.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={'LocationConstraint': region_name}
)
print(f"Bucket {bucket_name} created successfully in {region_name}.")

# 3. Disable Public Access Block
s3_client.put_public_access_block(
Bucket=bucket_name,
PublicAccessBlockConfiguration={
'BlockPublicAcls': False,
'IgnorePublicAcls': False,
'BlockPublicPolicy': False,
'RestrictPublicBuckets': False
}
)
print("Public access block disabled.")

# 4. Apply Bucket Policy for public read access
bucket_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": f"arn:aws:s3:::{bucket_name}/*"
}
]
}
s3_client.put_bucket_policy(
Bucket=bucket_name,
Policy=json.dumps(bucket_policy)
)
print("Bucket policy applied.")

# 5. Enable static website hosting
s3_client.put_bucket_website(
Bucket=bucket_name,
WebsiteConfiguration={
'IndexDocument': {'Suffix': 'index.html'},
'ErrorDocument': {'Key': 'error.html'}
}
)
print("Static website hosting enabled.")

# Output the public website URL dynamically mapped to the region
print(f"\nWebsite URL: http://{bucket_name}.s3-website-{region_name}.amazonaws.com")

アップロード試験

import io
import boto3
from PIL import ImageGrab

# 1. Initialize AWS session using the specific profile
session = boto3.Session(profile_name='resources_dev')
region_name = session.region_name
s3_client = session.client('s3', region_name=region_name)

bucket_name = 'bucket-test-20260813-dev0813'
object_key = 'image_files/clipboard_image.png'

# 2. Grab image from clipboard
print("Fetching image from clipboard...")
img = ImageGrab.grabclipboard()

# 3. Check if clipboard contains an image
if isinstance(img, io.IOBase) or img is None:
print("Error: No image found in the clipboard. Please copy an image first.")
else:
# 4. Convert image to bytes in memory (PNG format)
image_bytes = io.BytesIO()
img.save(image_bytes, format='PNG')
image_bytes.seek(0) # Reset stream pointer to the beginning

# 5. Upload to S3 with content type metadata
s3_client.upload_fileobj(
image_bytes,
bucket_name,
object_key,
ExtraArgs={'ContentType': 'image/png'} # Ensures it opens in browser instead of downloading
)
print(f"Success! Image uploaded to s3://{bucket_name}/{object_key}")
print(f"Public URL: http://{bucket_name}.s3-website-{region_name}.amazonaws.com/{object_key}")

ITとソフトウェア�の人気オンラインコースHP Directplus -HP公式オンラインストア-