[
  {
    "path": ".gitignore",
    "content": ".idea\n.serverless\n.DS_Store\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# TypeScript v1 declaration files\ntypings/\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variables file\n.env\n\n# next.js build output\n.next\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2019 Tobi\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# serverless-aws-static-websites\nHost your static website on AWS via S3, with global CDN via CloudFront, using SSL certificates provided by ACM using your own domain name!\n\nAll set up via one [Serverless](https://www.serverless.com) command and minimum manual configuration!\n\n## Architecture\n\n![Serverless static websites on AWS](docs/architecture.png)[]()\n\n### What is provisioned in your AWS account?\n* A S3 bucket containing your static website\n* A CloudFront distribution for global hosting via CDN\n* A HostedZone on Route53 with A records for your domain name\n* A Lambda function for automatic SSL certificate generation via ACM for your domain name (run once upon deployment)\n\n## Preconditions\nThis guide assumes that you have a pre-existing domain which you want to use for hosting your static website. Furthermore, you need to have access to the domain's DNS configuration.\n\nAlso, you need to have an install of [Serverless](https://www.serverless.com) on your machine.\n\n## How-to\nTo use this blueprint with your own static websites, you can follow the steps below to get started.\n\n### Set up a Serverless project for your static website\nThere are basically two ways to get started, either use [Serverless](https://www.serverless.com) to generate a basic project structure, or use the \"traditional\" fork and clone mechanisms.\n\n#### Use Serverless templates\nThe following command will create a local project structure you can use to deploy your static website in the `mystaticwebsite` folder relative to your current working directory:\n\n```bash\n$ sls create --template-url https://github.com/tobilg/serverless-aws-static-websites --path mystaticwebsite\nServerless: Generating boilerplate...\nServerless: Downloading and installing \"serverless-aws-static-websites\"...\nServerless: Successfully installed \"serverless-aws-static-websites\"\n```\n\n**Hint**  \nWhen using this method, Serverless is replacing the `service.name` in the `serverless.yml` file automatically with `mystaticwebiste`. If you want to use a different stack name, you have to replace it manually. You also need to take care of that the stack name is using only allowed characters. When using the \"Fork and clone\" method below, the stack name is automatically derived from the domain name and sanitized regarding the allowed characters.\n\n#### Fork and clone\nOnce you forked the repo on GitHub, you can clone it locally via\n\n```bash\n$ git clone git@github.com:youraccount/yourrepo.git\n```\n\nwhere `youraccount/yourrepo` needs to be replaced with the actual repository name of your forked repo.\n\n### Install dependencies\nTo install the dependencies, do a \n\n```bash\n$ npm i\n```\n\nAfter that, the project is usable.\n\n### Create your static website\nYou can now create your static website in the `src` folder of your cloned repo.\n\n### Deploy\nYou can deploy your static website with the following command:\n\n```bash\n$ sls deploy --domain yourdomain.yourtld\n```\n\nwhere `yourdomain.yourtld` needs to be replaced with your actual domain name. You can also specify a AWS region via the `--region` flag, otherwise `us-east-1` will be used.\n\n#### Manual update of DNS records on first deploy\nOn the first deploy, it is necessary to update the DNS setting for the domain manually, otherwise the hosted zone will not be able to be established.\n\nTherefore, once you triggered the `sls deploy` command, you need to log into the AWS console, go to the [Hosted Zones](https://console.aws.amazon.com/route53/home?region=eu-central-1#hosted-zones:) menu and select the corresponding domain name you used for the deployment.\n\nThe nameservers you have to configure your domain DNS to can be found under the `NS` record and will look similar to this:\n\n```bash\nns-1807.awsdns-33.co.uk.\nns-977.awsdns-58.net.\nns-1351.awsdns-40.org.\nns-32.awsdns-04.com.\n```\n\nYou should then update your DNS settings for your domain with those values, **otherwise the stack creation process will fail**.\n\nThis is a bit misfortunate, but to the best of knowledge there's currently no other way possible if you use AWS external (non-Route53) domains. During my tests with [namecheap.com](https://www.namecheap.com) domains the DNS records were always updated fast enough, so that the stack creation didn't fail.\n\n#### Deployment process duration\nAs a new CloudFront distribution is created (which is pretty slow), it can take **up to 45min** for the initial deploy to finish. This is normal and expected behavior.\n\n### Post-deploy\nIf the deployment finished successfully, you will be able to access your domain via `https://www.yourdomain.yourtld` and `https://yourdomain.yourtld`.\n\nThis setup should give you some good [PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights/?hl=en) results.\n\n### Updates\nFor every update of your website, you can trigger a deploy as stated above. This will effectively just do s S3 sync of the `src` folder. \n\nTo do a manual sync, your can also use `sls s3sync`. There's also the possibility to customize the caching behavior for individual files or file types via the `serverless.yml`, see the [s3sync plugin's documentation](https://www.npmjs.com/package/serverless-s3-sync#setup).\n\nAs **CloudFront caches the contents of the website**, a [Serverless plugin](https://github.com/aghadiry/serverless-cloudfront-invalidate) is used to invalidate files. This [may incur costs](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#PayingForInvalidation), see the [docs](https://aws.amazon.com/de/premiumsupport/knowledge-center/cloudfront-serving-outdated-content-s3/) for more info. \n\nYou can run `sls cloudfrontInvalidate` to do a standalone invalidation of the defined files in the `serverless.yml`.\n\n## Removal\nIf you want to remove the created stack, you will have to delete all records of the Hosted Zone of the respective domain except the `SOA` and `NS` records, otherwise the stack deletion via\n\n```bash\n$ sls remove --domain yourdomain.yourtld\n```\n\nwill fail.\n"
  },
  {
    "path": "modules/output.js",
    "content": "module.exports.handler = (data, serverless, options) => {\n    serverless.cli.log(`DNS nameservers to be configured with your '${serverless.providers.aws.options.domain}' domain: ${data.HostedZoneNameservers}`);\n};\n"
  },
  {
    "path": "modules/sanitizeStackName.js",
    "content": "module.exports.sanitize = (serverless) => {\n    if (!serverless.providers.aws.options.hasOwnProperty('domain')) {\n        serverless.cli.log('No domain flag found, exiting! Please specify --domain <domainName>');\n        process.exit(1);\n    } else {\n        const sanitizedStackName = `website-${serverless.providers.aws.options.domain.replace(/\\./g, '-')}`;\n        serverless.cli.log(`Stack name is ${sanitizedStackName}`);\n        return sanitizedStackName;\n    }\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"serverless-aws-static-websites\",\n  \"version\": \"0.1.0\",\n  \"description\": \"Deploy your static websites without all the hassle on AWS with CloudFront, S3, ACM and Route53 via Serverless\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git@github.com:tobilg/serverless-aws-static-websites.git\"\n  },\n  \"author\": \"\",\n  \"license\": \"UNLICENSED\",\n  \"bugs\": {\n    \"url\": \"https://github.com/tobilg/serverless-aws-static-websites/issues\"\n  },\n  \"homepage\": \"https://github.com/tobilg/serverless-aws-static-websites#readme\",\n  \"devDependencies\": {\n    \"serverless-cloudfront-invalidate\": \"^1.3.0\",\n    \"serverless-pseudo-parameters\": \"^2.4.0\",\n    \"serverless-s3-sync\": \"^1.8.0\",\n    \"serverless-stack-output\": \"^0.2.3\"\n  },\n  \"dependencies\": {}\n}\n"
  },
  {
    "path": "resources/certificate.yml",
    "content": "Resources:\n  SSLCertificate:\n    Type: 'Custom::DNSCertificate'\n    DependsOn:\n      - HostedZone\n    Properties:\n      DomainName: '${opt:domain}'\n      SubjectAlternativeNames:\n        - 'www.${opt:domain}'\n      ValidationMethod: DNS\n      # Needs to be in us-east-1 because of CloudFront limitations\n      Region: us-east-1\n      DomainValidationOptions:\n        - DomainName: '${opt:domain}'\n          HostedZoneId: '#{HostedZone}'\n      ServiceToken: '#{CustomAcmCertificateLambda.Arn}'\n"
  },
  {
    "path": "resources/cf-distribution.yml",
    "content": "# See https://blog.m-taylor.co.uk/2018/01/cloudformation-template-for-a-cloudfront-enabled-s3-website.html\nResources:\n  CFDistribution:\n    Type: 'AWS::CloudFront::Distribution'\n    DependsOn:\n      - WebsiteBucket\n      - HostedZone\n      - SSLCertificate\n      - CloudFrontOriginAccessIdentity\n    Properties:\n      DistributionConfig:\n        Aliases:\n          - '${opt:domain}'\n          - 'www.${opt:domain}'\n        Origins:\n          - DomainName: '#{WebsiteBucket.DomainName}'\n            OriginPath: ''\n            Id: S3BucketOrigin\n            S3OriginConfig:\n              OriginAccessIdentity:\n                Fn::Join:\n                  - ''\n                  - - 'origin-access-identity/cloudfront/'\n                    - '#{CloudFrontOriginAccessIdentity}'\n        Comment: 'CloudFront origin for ${opt:domain}'\n        DefaultCacheBehavior:\n          AllowedMethods:\n            - GET\n            - HEAD\n            - OPTIONS\n          TargetOriginId: S3BucketOrigin\n          Compress: true\n          ForwardedValues:\n            QueryString: 'false'\n            Cookies:\n              Forward: none\n          ViewerProtocolPolicy: redirect-to-https\n        DefaultRootObject: index.html\n        Enabled: 'true'\n        HttpVersion: 'http2'\n        PriceClass: 'PriceClass_100'\n        ViewerCertificate:\n          AcmCertificateArn: '#{SSLCertificate}'\n          SslSupportMethod: sni-only\n"
  },
  {
    "path": "resources/cloudfront-origin-access-identity.yml",
    "content": "Resources:\n  CloudFrontOriginAccessIdentity:\n    Type: 'AWS::CloudFront::CloudFrontOriginAccessIdentity'\n    Properties:\n      CloudFrontOriginAccessIdentityConfig:\n        Comment: '${self:service.name}-oai'"
  },
  {
    "path": "resources/custom-acm-certificate-lambda-role.yml",
    "content": "Resources:\n  CustomAcmCertificateLambdaExecutionRole:\n    Type: 'AWS::IAM::Role'\n    Properties:\n      AssumeRolePolicyDocument:\n        Statement:\n          - Action:\n              - sts:AssumeRole\n            Effect: Allow\n            Principal:\n              Service: lambda.amazonaws.com\n        Version: '2012-10-17'\n      ManagedPolicyArns:\n        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole\n        - arn:aws:iam::aws:policy/service-role/AWSLambdaRole\n      Policies:\n        - PolicyDocument:\n            Statement:\n              - Action:\n                  - acm:AddTagsToCertificate\n                  - acm:DeleteCertificate\n                  - acm:DescribeCertificate\n                  - acm:RemoveTagsFromCertificate\n                Effect: Allow\n                Resource:\n                  - 'arn:aws:acm:*:#{AWS::AccountId}:certificate/*'\n              - Action:\n                  - acm:RequestCertificate\n                  - acm:ListTagsForCertificate\n                  - acm:ListCertificates\n                Effect: Allow\n                Resource:\n                  - '*'\n              - Action:\n                  - route53:ChangeResourceRecordSets\n                Effect: Allow\n                Resource:\n                  - arn:aws:route53:::hostedzone/*\n            Version: '2012-10-17'\n          PolicyName: 'CustomAcmCertificateLambdaExecutionPolicy-${self:service.name}'\n"
  },
  {
    "path": "resources/custom-acm-certificate-lambda.yml",
    "content": "Resources:\n  CustomAcmCertificateLambda:\n    Type: 'AWS::Lambda::Function'\n    Metadata:\n      Source: https://github.com/dflook/cloudformation-dns-certificate\n      Version: 1.7.1\n    Properties:\n      Description: Cloudformation custom resource for DNS validated certificates\n      Handler: index.handler\n      Role: '#{CustomAcmCertificateLambdaExecutionRole.Arn}'\n      Runtime: python3.6\n      Timeout: 900\n      Code:\n        ZipFile: \"T=RuntimeError\\nimport copy,hashlib as t,json,logging as B,time\\\n          \\ as b\\nfrom boto3 import client as K\\nfrom botocore.exceptions import ClientError\\\n          \\ as u,ParamValidationError as v\\nfrom botocore.vendored import requests\\\n          \\ as w\\nA=B.getLogger()\\nA.setLevel(B.INFO)\\nD=A.info\\nS=A.exception\\nd=json.dumps\\n\\\n          M=copy.copy\\ne=b.sleep\\ndef handler(event,c):\\n\\tA9='OldResourceProperties';A8='Update';A7='Delete';A6='None';A5='acm';A4='FAILED';A3='properties';A2='stack-id';A1='logical-id';A0='DNS';s='Old';r='Certificate';q='LogicalResourceId';p='DomainName';o='ValidationMethod';n='Route53RoleArn';m='Region';a='RequestType';Z='Reinvoked';Y='StackId';X=None;R='Status';Q='Key';P='';O=True;N='DomainValidationOptions';L=False;J='ResourceProperties';I='cloudformation:';H='Value';G='CertificateArn';F='Tags';C='PhysicalResourceId';A=event;f=c.get_remaining_time_in_millis;D(A)\\n\\\n          \\tdef g():\\n\\t\\tD=M(B)\\n\\t\\tfor H in ['ServiceToken',m,F,n]:D.pop(H,X)\\n\\\n          \\t\\tif o in B:\\n\\t\\t\\tif B[o]==A0:\\n\\t\\t\\t\\tfor I in set([B[p]]+B.get('SubjectAlternativeNames',[])):k(I)\\n\\\n          \\t\\t\\t\\tdel D[N]\\n\\t\\tA[C]=E.request_certificate(IdempotencyToken=y,**D)[G];l()\\n\\\n          \\tdef U(a):\\n\\t\\twhile O:\\n\\t\\t\\ttry:E.delete_certificate(**{G:a});return\\n\\\n          \\t\\t\\texcept u as B:\\n\\t\\t\\t\\tS(P);A=B.response['Error']['Code']\\n\\t\\t\\t\\\n          \\tif A=='ResourceInUseException':\\n\\t\\t\\t\\t\\tif f()/1000<30:raise\\n\\t\\t\\t\\\n          \\t\\te(5);continue\\n\\t\\t\\t\\tif A in['ResourceNotFoundException','ValidationException']:return\\n\\\n          \\t\\t\\t\\traise\\n\\t\\t\\texcept v:return\\n\\tdef V(props):\\n\\t\\tfor J in E.get_paginator('list_certificates').paginate():\\n\\\n          \\t\\t\\tfor B in J['CertificateSummaryList']:\\n\\t\\t\\t\\tD(B);C={A[Q]:A[H]for\\\n          \\ A in E.list_tags_for_certificate(**{G:B[G]})[F]}\\n\\t\\t\\t\\tif C.get(I+A1)==A[q]and\\\n          \\ C.get(I+A2)==A[Y]and C.get(I+A3)==hash(props):return B[G]\\n\\tdef h():\\n\\\n          \\t\\tif A.get(Z,L):raise T('Certificate not issued in time')\\n\\t\\tA[Z]=O;D(A);K('lambda').invoke(FunctionName=c.invoked_function_arn,InvocationType='Event',Payload=d(A).encode())\\n\\\n          \\tdef i():\\n\\t\\twhile f()/1000>30:\\n\\t\\t\\tB=E.describe_certificate(**{G:A[C]})[r];D(B)\\n\\\n          \\t\\t\\tif B[R]=='ISSUED':return O\\n\\t\\t\\telif B[R]==A4:raise T(B.get('FailureReason',P))\\n\\\n          \\t\\t\\te(5)\\n\\t\\treturn L\\n\\tdef x():B=M(A[s+J]);B.pop(F,X);C=M(A[J]);C.pop(F,X);return\\\n          \\ B!=C\\n\\tdef j():\\n\\t\\tW='Type';V='Name';U='HostedZoneId';T='ValidationStatus';S='PENDING_VALIDATION';L='ResourceRecord'\\n\\\n          \\t\\tif B.get(o)!=A0:return\\n\\t\\twhile O:\\n\\t\\t\\tI=E.describe_certificate(**{G:A[C]})[r];D(I)\\n\\\n          \\t\\t\\tif I[R]!=S:return\\n\\t\\t\\tif not[A for A in I.get(N,[{}])if T not in\\\n          \\ A or L not in A]:break\\n\\t\\t\\tb.sleep(1)\\n\\t\\tfor F in I[N]:\\n\\t\\t\\tif\\\n          \\ F[T]==S:M=k(F[p]);P=M.get(n,B.get(n));J=K('sts').assume_role(RoleArn=P,RoleSessionName=(r+A[q])[:64],DurationSeconds=900)['Credentials']if\\\n          \\ P is not X else{};Q=K('route53',aws_access_key_id=J.get('AccessKeyId'),aws_secret_access_key=J.get('SecretAccessKey'),aws_session_token=J.get('SessionToken')).change_resource_record_sets(**{U:M[U],'ChangeBatch':{'Comment':'Domain\\\n          \\ validation for '+A[C],'Changes':[{'Action':'UPSERT','ResourceRecordSet':{V:F[L][V],W:F[L][W],'TTL':60,'ResourceRecords':[{H:F[L][H]}]}}]}});D(Q)\\n\\\n          \\tdef k(n):\\n\\t\\tC='.';n=n.rstrip(C);D={A[p].rstrip(C):A for A in B[N]};A=n.split(C)\\n\\\n          \\t\\twhile len(A):\\n\\t\\t\\tif C.join(A)in D:return D[C.join(A)]\\n\\t\\t\\tA=A[1:]\\n\\\n          \\t\\traise T(N+' missing'+' for '+n)\\n\\thash=lambda v:t.new('md5',d(v,sort_keys=O).encode()).hexdigest()\\n\\\n          \\tdef l():B=M(A[J].get(F,[]));B+=[{Q:I+A1,H:A[q]},{Q:I+A2,H:A[Y]},{Q:I+'stack-name',H:A[Y].split('/')[1]},{Q:I+A3,H:hash(A[J])}];E.add_tags_to_certificate(**{G:A[C],F:B})\\n\\\n          \\tdef W():D(A);B=w.put(A['ResponseURL'],json=A,headers={'content-type':P});B.raise_for_status()\\n\\\n          \\ttry:\\n\\t\\ty=hash(A['RequestId']+A[Y]);B=A[J];E=K(A5,region_name=B.get(m));A[R]='SUCCESS'\\n\\\n          \\t\\tif A[a]=='Create':\\n\\t\\t\\tif A.get(Z,L)is L:A[C]=A6;g()\\n\\t\\t\\tj()\\n\\\n          \\t\\t\\tif not i():return h()\\n\\t\\telif A[a]==A7:\\n\\t\\t\\tif A[C]!=A6:\\n\\t\\t\\\n          \\t\\tif A[C].startswith('arn:'):U(A[C])\\n\\t\\t\\t\\telse:U(V(B))\\n\\t\\telif A[a]==A8:\\n\\\n          \\t\\t\\tif x():\\n\\t\\t\\t\\tD(A8)\\n\\t\\t\\t\\tif V(B)==A[C]:\\n\\t\\t\\t\\t\\ttry:E=K(A5,region_name=A[A9].get(m));D(A7);U(V(A[A9]))\\n\\\n          \\t\\t\\t\\t\\texcept:S(P)\\n\\t\\t\\t\\t\\treturn W()\\n\\t\\t\\t\\tif A.get(Z,L)is L:g()\\n\\\n          \\t\\t\\t\\tj()\\n\\t\\t\\t\\tif not i():return h()\\n\\t\\t\\telse:\\n\\t\\t\\t\\tif F in\\\n          \\ A[s+J]:E.remove_tags_from_certificate(**{G:A[C],F:A[s+J][F]})\\n\\t\\t\\t\\t\\\n          l()\\n\\t\\telse:raise T(A[a])\\n\\t\\treturn W()\\n\\texcept Exception as z:S(P);A[R]=A4;A['Reason']=str(z);return\\\n          \\ W()\"\n"
  },
  {
    "path": "resources/dns-records.yml",
    "content": "# See RecordSet: https://docs.aws.amazon.com/de_de/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html\n# See AliasTarget: https://docs.aws.amazon.com/de_de/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html\n# See https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region (below the first table for hosted zone ids / website endpoints of S3)\nResources:\n  DnsRecord:\n    Type: 'AWS::Route53::RecordSet'\n    DependsOn:\n      - HostedZone\n    Properties:\n      Comment: 'Alias CloudFront for ${opt:domain}'\n      HostedZoneId: '#{HostedZone}'\n      Type: A\n      Name: '${opt:domain}'\n      AliasTarget:\n        # Generated domain name from CloudFront\n        DNSName: '#{CFDistribution.DomainName}'\n        # Default (static) hosted zone for CloudFront\n        HostedZoneId: 'Z2FDTNDATAQYW2'\n  WWWDnsRecord:\n    Type: 'AWS::Route53::RecordSet'\n    DependsOn:\n      - HostedZone\n    Properties:\n      Comment: 'Alias CloudFront for www.${opt:domain}'\n      HostedZoneId: '#{HostedZone}'\n      Type: A\n      Name: 'www.${opt:domain}'\n      AliasTarget:\n        # Generated domain name from CloudFront\n        DNSName: '#{CFDistribution.DomainName}'\n        # Default (static) hosted zone for CloudFront\n        HostedZoneId: 'Z2FDTNDATAQYW2'"
  },
  {
    "path": "resources/hosted-zone.yml",
    "content": "# See https://docs.aws.amazon.com/de_de/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone.html\nResources:\n  HostedZone:\n    Type: 'AWS::Route53::HostedZone'\n    Properties:\n      HostedZoneConfig:\n        Comment: 'Hosted zone for ${opt:domain}'\n      Name: '${opt:domain}'"
  },
  {
    "path": "resources/outputs.yml",
    "content": "Outputs:\n  CloudFrontDistributionId:\n    Description: CloudFront distribution id\n    Value:\n      Ref: CFDistribution\n  HostedZoneNameservers:\n    Description: The nameservers for the Hosted Zone (to be used with your external DNS configuration)\n    Value:\n      'Fn::Join':\n        - ', '\n        - 'Fn::GetAtt': ['HostedZone', 'NameServers']"
  },
  {
    "path": "resources/s3-bucket.yml",
    "content": "Resources:\n  WebsiteBucket:\n    Type: 'AWS::S3::Bucket'\n    Properties:\n      BucketName: ${opt:domain}\n"
  },
  {
    "path": "resources/s3-policies.yml",
    "content": "Resources:\n  WebsiteBucketPolicy:\n    Type: AWS::S3::BucketPolicy\n    DependsOn:\n      - WebsiteBucket\n    Properties:\n      Bucket:\n        Ref: WebsiteBucket\n      PolicyDocument:\n        Statement:\n          - Sid: PublicReadGetObject\n            Effect: Allow\n            Principal:\n              AWS:\n                Fn::Join:\n                  - ' '\n                  - - 'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity'\n                    - '#{CloudFrontOriginAccessIdentity}'\n            Action:\n              - s3:GetObject\n            Resource:\n              - Fn::Join: [\n                  '', [\n                    'arn:aws:s3:::',\n                    {\n                      'Ref': 'WebsiteBucket'\n                    },\n                    '/*'\n                  ]\n                ]\n"
  },
  {
    "path": "serverless.yml",
    "content": "service:\n  name: ${file(./modules/sanitizeStackName.js):sanitize}\n\nplugins:\n  - serverless-s3-sync\n  - serverless-pseudo-parameters\n  - serverless-stack-output\n  - serverless-cloudfront-invalidate\n\ncustom:\n\n  # The domain name to be used\n  domainName: ${opt:domain}\n\n  # Output plugin configuration\n  output:\n    handler: modules/output.handler\n\n  # CloudFront invalidation plugin configuration\n  cloudfrontInvalidate:\n    distributionIdKey: 'CloudFrontDistributionId'\n    items: # Add your files to invalidate here:\n      - '/index.html'\n\n  # S3 sync plugin configuration\n  s3Sync:\n    - bucketName: ${opt:domain}\n      localDir: src\n\nprovider:\n  name: aws\n  runtime: nodejs8.10\n  region: ${opt:region, 'us-east-1'}\n\nresources:\n\n  - ${file(resources/custom-acm-certificate-lambda.yml)}\n  - ${file(resources/custom-acm-certificate-lambda-role.yml)}\n  - ${file(resources/cloudfront-origin-access-identity.yml)}\n  - ${file(resources/s3-bucket.yml)}\n  - ${file(resources/s3-policies.yml)}\n  - ${file(resources/hosted-zone.yml)}\n  - ${file(resources/dns-records.yml)}\n  - ${file(resources/certificate.yml)}\n  - ${file(resources/cf-distribution.yml)}\n  - ${file(resources/outputs.yml)}\n"
  },
  {
    "path": "src/index.html",
    "content": "<html>\n<body>\n<h1>Welcome to my static website!</h1>\n</body>\n</html>"
  }
]