Despliegue de una web estática con S3 + CloudFront

Despligue de una web estática en S3 + CloudFront

Static Web S3

Objetivo:

Desplegar una web estática en S3 y añadir CloudFront como CDN.

Tarea1: Despliegue de una web estática en S3

Sigue las instrucciones de https://docs.aws.amazon.com/AmazonS3/latest/userguide/HostingWebsiteOnS3Setup.html

  • Crear un bucket S3
  • Configurar el bucket para que sea accesible como web estática
  • Añade los ficheros de una de las webs estáticas del ejercicio anterior. Puedes subirlos desde la misma interfaz web de la consola de AWS. Veremos también cómo puedes hacerlo desde AWS CLI.

Tarea2: Añadir CloudFront como CDN

Sigue el ejemplo de https://aws.amazon.com/es/blogs/aws-spanish/como-alojar-tu-sitio-web-estatico-en-amazon-s3-y-amazon-cloudfront/

Nosotros no integraremos AWS CodePipeline, AWS CodeCommit y AWS CodeBuild.

Aquí tienes un ejemplo paso a paso:

1 - Despliegue de una web hecha con Hugo en S3

Despligue de una web estática con Hugo en S3 + CloudFront

Pasos

Previo

Configurar AWS CLI

  • Conecta con el Learner Lab
  • Copia las credentials de tu usuario de IAM en ~/.aws/credentials

Configurar hugo.yml

Ejemplo

[deployment]
# By default, files are uploaded in an arbitrary order.
# Files that match the regular expressions in the "Order" list
# will be uploaded first, in the listed order.
order = [".jpg$", ".gif$"]


[[deployment.targets]]
# An arbitrary name for this target.
name = "mydeployment"

# S3; see https://gocloud.dev/howto/blob/#s3
# For S3-compatible endpoints, see https://gocloud.dev/howto/blob/#s3-compatible
URL = "s3://<Bucket Name>?region=<AWS region>" # Configura aquí tu bucket

# If you are using a CloudFront CDN, deploy will invalidate the cache as needed.
cloudFrontDistributionID = <ID>  # Sólo si quieres usar cloudfront

# Optionally, you can include or exclude specific files.
# See https://godoc.org/github.com/gobwas/glob#Glob for the glob pattern syntax.
# If non-empty, the pattern is matched against the local path.
# All paths are matched against in their filepath.ToSlash form.
# If exclude is non-empty, and a local or remote file's path matches it, that file is not synced.
# If include is non-empty, and a local or remote file's path does not match it, that file is not synced.
# As a result, local files that don't pass the include/exclude filters are not uploaded to remote,
# and remote files that don't pass the include/exclude filters are not deleted.
# include = "**.html" # would only include files with ".html" suffix
# exclude = "**.{jpg, png}" # would exclude files with ".jpg" or ".png" suffix


# [[deployment.matchers]] configure behavior for files that match the Pattern.
# See https://golang.org/pkg/regexp/syntax/ for pattern syntax.
# Pattern searching is stopped on first match.

# Samples:

[[deployment.matchers]]
# Cache static assets for 1 year.
pattern = "^.+\\.(js|css|svg|ttf)$"
cacheControl = "max-age=31536000, no-transform, public"
gzip = true

[[deployment.matchers]]
pattern = "^.+\\.(png|jpg)$"
cacheControl = "max-age=31536000, no-transform, public"
gzip = false

[[deployment.matchers]]
# Set custom content type for /sitemap.xml
pattern = "^sitemap\\.xml$"
contentType = "application/xml"
gzip = true

[[deployment.matchers]]
pattern = "^.+\\.(html|xml|json)$"
gzip = true

Crear web

Genera la web en el directorio public

$ hugo

Desplegar web

$ hugo deploy

2 - Crear web estática en S3 con CLI

Crear Web estática en S3 con AWS CLI

Pasos

Previo

Configurar AWS CLI

  • Conecta con el Learner Lab
  • Copia las credentials de tu usuario de IAM en ~/.aws/credentials

Crear Bucket S3


bucket_name="miwebs3-nombre-bucket-unico"

aws s3api create-bucket --bucket "${bucket_name}"

Configuramos el bucket para que sea publico

aws s3api put-public-access-block --bucket "${bucket_name}" --public-access-block-configuration "BlockPublicPolicy=false"

aws s3api put-bucket-policy --bucket "${bucket_name}" --policy '{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::'"${bucket_name}"'/*"
 
            ]
        }
    ]
}'

Subimos un fichero html

Mostramos un ejemplo, puedes subir tu web estática

echo "<html><center><h1>My Static Website on S3</h1></center></html>" > index.html

aws s3 cp index.html s3://"${bucket_name}"

Configuramos el bucket para que sea un sitio web

aws s3 website s3://"${bucket_name}" --index-document index.html

Comprobamos que funciona

curl http://"${bucket_name}".s3-website.us-east-1.amazonaws.com