LoginSignup
12

More than 1 year has passed since last update.

aws-cliを使ってS3で静的コンテンツを公開する

Last updated at Posted at 2015-07-22

※こちらの記事は個人ブログに移行しました。

#前提

  • aws-cliが入っていること

  • IAMのパーミッションがいい感じに設定されていること

  • Credentialがconfigureもしくは環境変数に設定されてること
    --profile使ってもいいです

  • default region が ap-northeast-1 で設定してあること
    ※ 別にいいんだけど適宜いい感じに読み替えて下さい

  • Mac想定してるのでWindowsの人はEC2使うとかいい感じに読み替えるとかしてください

  • loggingの設定はこの手順には含まれてません

#手順

  1. バケットの作成
  2. コンテンツの設置
  3. Static Website Hostingを有効にする
  4. BucketPolicyを設定する

##バケットの作成

command
$ BUCKET_NAME=backetnonamae
$ aws s3 mb s3://${BUCKET_NAME}
出力結果
make_bucket: s3://backetnonamae/

##コンテンツの設置
コンテンツはカレントディレクトリにあるものとして記載しています。
置いてあるファイルは/index.html/css/index.cssの2つです。

command
$ SC_DIR=$(pwd)
$ aws s3 sync ${SC_DIR}/ s3://${BUCKET_NAME}/
出力結果
upload: css/index.css to s3://backetnonamae/css/index.css
upload: ./index.html to s3://backetnonamae/index.html

##Static Website Hostingを有効にする

command
$ aws s3 website s3://${BUCKET_NAME} --index-document index.html
出力結果
(なし)

##BucketPolicyを設定する
このポリシーを適用することでアップロードしたファイルはすべてpublicになります。
###ポリシー用のjson作成

command
$ PUBLIC_POLICY=public.json
$ cat << EOF > ${PUBLIC_POLICY}
{
	"Version": "2012-10-17",
	"Id": "PublicRead",
	"Statement": [
		{
			"Sid": "ReadAccess",
			"Effect": "Allow",
			"Principal": "*",
			"Action": "s3:GetObject",
			"Resource": "arn:aws:s3:::${BUCKET_NAME}/*"
		}
	]
}
EOF
public.json
{
	"Version": "2012-10-17",
	"Id": "PublicRead",
	"Statement": [
		{
			"Sid": "ReadAccess",
			"Effect": "Allow",
			"Principal": "*",
			"Action": "s3:GetObject",
			"Resource": "arn:aws:s3:::backetnonamae/*"
		}
	]
}

###ポリシーの適用

command
$ aws s3api put-bucket-policy --bucket ${BUCKET_NAME} --policy file://${PUBLIC_POLICY}
出力結果
(なし)

###表示確認

command
$ open http://${BUCKET_NAME}.s3-website-ap-northeast-1.amazonaws.com

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12