exanubes

Static Hosting #4AWS Code Pipeline with S3 Deployment from Github Repository

This article is part of a series:

  1. Hosting a static website on Amazon S3 with SSL
  2. Creating a cloudfront distribution for an s3 bucket
  3. Fix Cloudfront 404 errors when visiting direct URLs
  4. AWS Code Pipeline with S3 Deployment from Github Repository

In this article we will learn how to create aws-cdk infrastructure for deploying a React application from Github using a CI/CD pipeline. The idea behind this infrastructure is to build an automated pipeline which will download the code from github whenever someone pushes new code to it. Then we will need to install all dependencies and build the app after which we want to send all those production files to s3 and serve it with CloudFront.

To follow along, you will need an SSL Certificate in us-east-1 region, a github personal access token which will be stored in AWS Secrets Manager. It would also be good to have a Route 53 hosted zone, but it's not required. If you have a domain name outside of AWS and would like to use it for this, you might wanna see how to share one domain across aws accounts.

Introduction #

For the purposes of this article, I have created a sample project in gatsby.js and I will be using aws-cdk v2 to create the required infrastructure. You can find the finished code on Github.

S3 Bucket #

First and foremost, we need an S3 Bucket that will hold the static files for our website.

ts
Double click to copy
1// lib/distribution.stack.ts
2export class DistributionStack extends Stack {
3 public readonly bucket: IBucket;
4
5 constructor(app: Construct, id: string, props: StackProps) {
6 super(app, id, props);
7 this.bucket = new Bucket(this, 'deploy-bucket', {
8 publicReadAccess: true,
9 bucketName: 'static-hosting-bucket',
10 removalPolicy: RemovalPolicy.DESTROY,
11 autoDeleteObjects: true,
12 websiteIndexDocument: 'index.html',
13 });
14 }
15}

A couple of things to note:

  • publicReadAccess has to be set to true because we want to host the website from the bucket thus everyone needs to be able to access the files. With that being said, do not store any sensitive data there. By default, all buckets are completely locked down.
  • bucketName, this one is optional, but keep in mind bucket names are global per region because they each have their own url. Make sure it's something unique or it will fail during deployment.
  • removalPolicy, we want to destroy the bucket when tearing down the infrastracture
  • autoDeleteObjects, makes removalPolicy possible. This will actually create a lambda function that will remove all objects from your s3 bucket so that cloudformation can delete the bucket. Only empty buckets can be deleted.
  • websiteIndexDocument is crucial. This not only points to the entry file for the application but also configures the bucket for static hosting

So, this bucket is ready for static hosting and now we can use it as target for our build output in the pipeline.

Pipeline #

At this point, we're already gonna need a Personal Access Token from Github which you can generate in the developer settings. Then go to AWS Secrets Manager for your region and create a plaintext secret.

This is necessary, because we need to give AWS Code Pipeline access to our github account so that it can download the source code from private repositories.

Getting source code into Code Pipeline #

ts
Double click to copy
1// lib/pipeline.stack.ts
2const SECRET_ARN = 'arn:aws:secretsmanager:us-east-1:12345678901234:secret:github/secret-7ncpR7'
3
4export class PipelineStack extends Stack {
5 constructor(scope: Construct, id: string, props: StackProps) {
6 super(scope, id, props);
7 new GitHubSourceCredentials(this, 'code-build-credentials', {
8 accessToken: SecretValue.secretsManager('github/cdk-pipeline')
9 })
10 const source = Source.gitHub({
11 owner: 'exanubes',
12 repo: 'aws-pipeline',
13 webhook: true,
14 webhookFilters: [
15 FilterGroup.inEventOf(EventAction.PUSH).andBranchIs('master')
16 ]
17 })

Here, we are setting the credentials that will be used by Code Build to communicate with the GitHub API. Next, define the source by pointing at your account and the repo it's supposed to use. Setting up a webhook is necessary to trigger the pipeline automatically when there are new commits on branch of your choice.

Building the application #

Now that our pipeline has access to the code we can utilise AWS Code Build to actually build the application.

typescript
Double click to copy
1// lib/pipeline.stack.ts
2 constructor(){
3 // ...
4 const buildSpec = this.getBuildSpec();
5 const project = new Project(this, 'project', {
6 projectName: 'pipeline-project',
7 source,
8 environment: {
9 buildImage: LinuxBuildImage.STANDARD_5_0,
10 privileged: true,
11 },
12 buildSpec
13 })
14 }
15 private getBuildSpec() {
16 return BuildSpec.fromObject({
17 version: '0.2',
18 env: {
19 shell: 'bash'
20 },
21 phases: {
22 pre_build: {
23 commands: [
24 'echo Build started on `date`',
25 'aws --version',
26 'node --version',
27 'npm install',
28 ],
29 },
30 build: {
31 commands: [
32 'npm run build',
33 ],
34 },
35 post_build: {
36 commands: [
37 'echo Build completed on `date`',
38 ]
39 }
40 },
41 artifacts: {
42 ['base-directory']: 'public',
43 files: ['**/*']
44 },
45 cache: {
46 paths: ['node_modules/**/*']
47 }
48 })
49 }

Projects are what Code Build uses to, well, build projects. So we had to create one, pass it a source – which is our github repo and we also had to pass it a build spec.

Build spec are instructions for the service on how to handle the build process. Phases are self explanatory, however, version – at least at the time of writing – has to be set to 0.2 similar to how in cloudformation we need to provide a version.

This is not the version of your build, it's the version of the buildSpec API we're using.

In artifacts we want to select what will be the output of the build step in our pipeline. Base Directory maps the "current location" to public and then in files we specify that we want to take everything within the public folder with the **/* glob pattern.

Permissions #

Before we go and build the pipeline we need to sort out permissions first

ts
Double click to copy
1// lib/pipeline.stack.ts
2
3interface Props extends StackProps {
4 bucket: IBucket;
5}
6
7constructor(scope: Construct, id: string, props: Props) {
8// ...
9 project.addToRolePolicy(new PolicyStatement({
10 actions: ["secretsmanager:GetSecretValue"],
11 resources: [SECRET_ARN]
12 }))
13 props.bucket.grantReadWrite(project.grantPrincipal)
14}

So first, we need to give the project permission to actually access the secret with Github access token and we also need it to have permission to read and write data from the S3 bucket.

Putting it together into a pipeline #

ts
Double click to copy
1// lib/pipeline.stack.ts
2const artifacts = {
3 source: new Artifact('Source'),
4 build: new Artifact('BuildOutput'),
5};

First we create artifacts that will be the results of each step. We have a source step which downloads the files from github – a Source Artifact – and a build step which creates the production ready application – a Build Artifact.

ts
Double click to copy
1// lib/pipeline.stack.ts
2const pipelineActions = {
3 source: new GitHubSourceAction({
4 actionName: 'Github',
5 owner: 'exanubes',
6 repo: 'aws-pipeline',
7 branch: 'master',
8 oauthToken: SecretValue.secretsManager('github/cdk-pipeline'),
9 output: artifacts.source,
10 trigger: GitHubTrigger.WEBHOOK,
11 }),
12 build: new CodeBuildAction({
13 actionName: 'CodeBuild',
14 project,
15 input: artifacts.source,
16 outputs: [artifacts.build],
17 }),
18 deploy: new S3DeployAction({
19 actionName: 'S3Deploy',
20 bucket: props.bucket,
21 input: artifacts.build,
22 }),
23};
24
25const pipeline = new Pipeline(this, 'DeployPipeline', {
26 pipelineName: `s3-pipeline`,
27 stages: [
28 { stageName: 'Source', actions: [pipelineActions.source] },
29 { stageName: 'Build', actions: [pipelineActions.build] },
30 { stageName: 'Deploy', actions: [pipelineActions.deploy] },
31 ],
32});

Here we actually use the setup prepared earlier and create Pipeline Actions. First the github action will download new source code and put it in the Source Artifact which is then picked up as input by the build action. The result of the build stage is put in the Build Artifact and deploy stage takes that as input and sends it over to the S3 bucket we created earlier.

Recap #

Thus far we have created an S3 bucket that is configured for public access and static hosting. Then we passed that bucket into the Pipeline stack. Next, we needed to setup a source and configure a webhook for triggering the pipeline automatically with new commits. That github source is then used in the Code Build project which builds the app based on the build spec we provided it with and outputs chosen files as artifact. Last but not least, we had to define the pipeline actions and use those actions to create the pipeline itself.

By this point this infrastructure is fully functional and the application can be seen by visiting the bucket's url. In the next few steps we will setup a cloudfront distribution with https and a custom domain.

Distribution #

Edge Function #

First of all, we're going to need a Lambda@Edge function as a request url proxy. I won't be going into reasons why in this article, but you can read about fixing Cloudfront 404 errors when visiting URLs.

ts
Double click to copy
1// lib/distribution.stack.ts
2const edgeLambda = new cloudfront.experimental.EdgeFunction(
3 this,
4 'request-url-proxy',
5 {
6 runtime: Runtime.NODEJS_14_X,
7 handler: 'edge-lambda.main',
8 code: Code.fromAsset(path.join(__dirname, '../src/', `edge-lambda`)),
9 memorySize: 128,
10 logRetention: RetentionDays.ONE_DAY,
11 tracing: Tracing.DISABLED, // x-ray tracing
12 currentVersionOptions: {
13 removalPolicy: RemovalPolicy.DESTROY,
14 },
15 }
16);

Not much to say about this pretty standard lambda setup where we define the runtime, memory and point to the file. The only difference is that it will be executed at edge locations where it will map URLs to .html files.

AWS requires that stacks which use Edge Functions also have an explicitly set region. We can either set it with a hard-coded string e.g. 'na-north-1' or we could use AWS SDK.

ts
Double click to copy
1// utils/index.ts
2const { ConfigServiceClient } = require('@aws-sdk/client-config-service');
3const client = new ConfigServiceClient({});
4
5export async function getRegion() {
6 return client.config.region();
7}
8
9// bin/aws-code-pipeline-with-s3-deployment.ts
10async function main() {
11 const app = new cdk.App();
12 const region = await getRegion();
13 const distribution = new DistributionStack(app, DistributionStack.name, {
14 env: { region },
15 });
16 new PipelineStack(app, PipelineStack.name, {
17 bucket: distribution.bucket,
18 env: { region },
19 });
20}

Cloudfront Distribution #

ts
Double click to copy
1// lib/distribution.stack.ts
2const certificate = Certificate.fromCertificateArn(
3 this,
4 'cloudfront-ssl-certificate',
5 certificateArn
6);
7const distribution = new Distribution(this, 'distribution', {
8 defaultBehavior: {
9 origin: new S3Origin(this.bucket),
10 edgeLambdas: [
11 {
12 functionVersion: edgeLambda.currentVersion,
13 eventType: LambdaEdgeEventType.VIEWER_REQUEST,
14 },
15 ],
16 viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
17 },
18 certificate,
19 defaultRootObject: 'index.html',
20 domainNames: ['www.dev.exanubes.com', 'dev.exanubes.com'],
21});

At this point we need to create the cloudfront distribution and point it to where our files are – S3 Bucket. We also have to configure it as a trigger for our Edge Function at every Viewer Request – read about assigning lambdas to cloudfront distributions to learn more. Also, CloudFront supports https protocol, so we can provide it an SSL certificate for the domains we want to use. It will work regardless but only through http. Default root object is the entry file for the application and domain names are access points – keep in mind you will need an Alias/CNAME Records for each of them.

Creating DNS Records #

Now, as mentioned above we need to create records for the domains and we're going to need as Hosted Zone for that. If you don't have a aws hosted zone for your domain, you can read about creating one here.

ts
Double click to copy
1// lib/distribution.stack.ts
2const hostedZone = HostedZone.fromHostedZoneAttributes(this, 'hosted-zone', {
3 hostedZoneId: 'Z09747622HB25HPBEB7U5',
4 zoneName: 'dev.exanubes.com',
5});

So, dev.exanubes.com is the hosted zone of my choice. I will be using its apex domain as well as the www subdomain addresses for the application so, I need two DNS Records – one for each address.

ts
Double click to copy
1// lib/distribution.stack.ts
2new CnameRecord(this, 'www.cname', {
3 zone: hostedZone,
4 recordName: 'www',
5 domainName: distribution.distributionDomainName,
6});
7new ARecord(this, 'apex.alias', {
8 zone: hostedZone,
9 target: RecordTarget.fromAlias(new targets.CloudFrontTarget(distribution)),
10});

When creating any record, we have to provide the hostedZone. In the CName we also provide the subdomain – www – and point to our CloudFront Distribution. However, CName Records cannot be assigned to apex domains, and A Records are used for translating URLs into IP addresses. This leaves us with an alias record – which is a special type of A Record – that allows targeting any AWS Resource.

Summary #

In this article we have covered how to create an S3 Bucket configured for static hosting and serve that application via CloudFront with a custom domain and SSL Certificate. We were also able to automate the deployment process by creating a webhook for a github repository and providing access via a Personal Access Token. Then, we defined each step of the pipeline and designed the flow where each subsequent stage relied on Artifacts created in the previous one. In the end we finished with a completely automated workflow for our application. Nice.

Thanks!

A verification email has been sent to

Keep in Touch

Join other developers in Exanubes Newsletter

© 2022