<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michael Salisbury on Medium]]></title>
        <description><![CDATA[Stories by Michael Salisbury on Medium]]></description>
        <link>https://medium.com/@msalisbu?source=rss-982bed7165e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kxI7MEMLsYhjlzP6ve2NKA.jpeg</url>
            <title>Stories by Michael Salisbury on Medium</title>
            <link>https://medium.com/@msalisbu?source=rss-982bed7165e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:40:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@msalisbu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Running docker on ECS Fargate, with automated deployments, secrets, SSL and more!]]></title>
            <link>https://medium.com/@msalisbu/running-docker-on-ecs-fargate-with-automated-deployments-secrets-ssl-and-more-a93231be5dae?source=rss-982bed7165e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a93231be5dae</guid>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[fargate]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Michael Salisbury]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 20:00:18 GMT</pubDate>
            <atom:updated>2024-03-04T20:00:18.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgUu0NzRfDefhM-ahrHUDg.png" /><figcaption>msalisbu.com</figcaption></figure><p>As a DevOps engineer, knowing how to deploy docker is an essential job function to any org. Knowing how to deploy docker applications *well* is a completely different story. I’ve seen my fair share of half baked “production” deployments that were merely POC’s that ended up being used as prod, which create a level of fear and uncertainty when it comes to reliability, change control and even deployments. Everyone in the org suffers with unpredictable infra, and toil starts to spiral. I wanted to create this guide to help lay out some basic concepts, and hopefully help anyone wanting to use ECS start things off on the right foot.</p><p>When it comes to running containers on AWS, ECS is my preferred orchestrator. There are many solutions out there to achieve the same goal, but in terms of ease of support, scalability and reliability, it&#39;s a good choice for 99% of workloads and especially if you’re on AWS already.</p><p>This guide will be long, and honestly it’s written for those who are already considering or have a requirement to use ECS. I’m not here to convince you to use it, or take a stance on any tools, I’m just here to help those in similar situations.</p><h4>Prerequisites</h4><ul><li>An AWS account with a valid payment method.</li><li>A domain in Route53.</li><li>GitHub account and basic git knowledge.</li></ul><h3>Create a docker image, then automate deploying to ECR.</h3><p>The first step for this guide is having something to deploy. We’re going to set up a very simple docker app that hosts a web page, and prints environment variables as a proof of concept. We’re going to pass 3 vars to the container environment, one from the dockerfile, one from ECR and one from Secrets Manager.</p><p>Create a new git repository, and create a dockerfile with the following:</p><pre>#Python as the base image<br>FROM python:3.9-slim<br><br># Set the working directory in the container<br>WORKDIR /app<br><br># Copy the current directory contents into the container at /app<br>COPY . /app<br><br># Install Flask<br>RUN pip install Flask<br><br># Expose the port the app runs on<br>EXPOSE 8000<br><br># Define environment variable. Other vars will come from the task definitiin<br>ENV SECRET_FROM_DOCKERFILE=&quot;This is a variable from the dockerfile!&quot;<br><br># Run the Flask app<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>Create app.py with the following:</p><pre>from flask import Flask<br>import os<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;)<br>def index():<br>    # Store vars from the container&#39;s environment as my_variable1, my_variable2 and my_variable3<br>    my_variable1 = os.getenv(&#39;SECRET_FROM_ECS&#39;, &#39;First environment variable not set&#39;)<br>    my_variable2 = os.getenv(&#39;SECRET_FROM_SM&#39;, &#39;Second environment variable not set&#39;)<br>    my_variable3 = os.getenv(&#39;SECRET_FROM_DOCKERFILE&#39;, &#39;Second environment variable not set&#39;)<br>    return f&#39;&lt;h1&gt;{my_variable1}&lt;/h1&gt;&lt;br&gt;&lt;h1&gt;{my_variable2}&lt;/h1&gt;&lt;br&gt;&lt;h1&gt;{my_variable3}&lt;/h1&gt;&#39;<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=8000)</pre><p>This container runs a tiny flask app on port 8000, and prints variables from the containers environment to a webpage. I have each variable explicitly say where it’s from, so we can ensure secrets are getting fetched properly.</p><p>Build and run the container to test:</p><pre>docker build -t &lt;image_name&gt; .<br>docker run -d -p 8000:8000 &lt;image_name&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_3g6rPIuzCeqYSyvDfF5w.png" /></figure><p>You should see the above output in a browser. It should show the value from the variable we set in the dockerfile, and the other two won’t work since we haven’t set them up yet.</p><p>Next we’re going to start setting things up on AWS. You should create a new IAM user for this project, with the following policy. Create an access key and secret, and configure it locally with AWS CLI. Keep the keys handy as we’ll need them for GitLab actions.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;iam:PassRole&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringLike&quot;: {<br>                    &quot;iam:PassedToService&quot;: &quot;ecs-tasks.amazonaws.com&quot;<br>                }<br>            }<br>        },<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor1&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;iam:PassRole&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:iam::&lt;aws_account_number&gt;:role/arn:aws:iam::*:role/ecsInstanceRole*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringLike&quot;: {<br>                    &quot;iam:PassedToService&quot;: [<br>                        &quot;ec2.amazonaws.com&quot;,<br>                        &quot;ec2.amazonaws.com.cn&quot;<br>                    ]<br>                }<br>            }<br>        },<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor2&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;iam:CreateServiceLinkedRole&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringLike&quot;: {<br>                    &quot;iam:AWSServiceName&quot;: [<br>                        &quot;autoscaling.amazonaws.com&quot;,<br>                        &quot;ecs.amazonaws.com&quot;,<br>                        &quot;ecs.application-autoscaling.amazonaws.com&quot;,<br>                        &quot;spot.amazonaws.com&quot;,<br>                        &quot;spotfleet.amazonaws.com&quot;<br>                    ]<br>                }<br>            }<br>        },<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor3&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;secretsmanager:*&quot;,<br>                &quot;ecs:*&quot;,<br>                &quot;ecr:*&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><blockquote><strong>This is NOT intended for production, it’s intentionally permissive for the purpose of this demo. If you’re doing this in prod, PLEASE scope your permissions and resources appropriately. “Resource”: “*” should scare you whenever you see it.</strong></blockquote><p>Create an ECR repository by going to Amazon ECR, Private registry &gt; Repositories &gt; Create repository. Name it something appropriate, and hit create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Dn31yCWiN2DVdwk79gzJA.png" /></figure><p>In your GitHub repo, go to Actions and select enable actions for this repo. Then head to Settings &gt; Secrets and Variables &gt; Actions. Select New Repository Secret, name it AWS_ACCESS_KEY_ID, and paste your access key ID. Do the same for AWS_SECRET_ACCESS_KEY.</p><p>We’ll need to commit the actions config, in your repo create .github/workflows/config.yml with the following:</p><pre>name: Build &amp; Deploy to ECR &amp; ECS<br>on:<br>  push:<br>    branches:<br>      - main<br><br>env:<br>  AWS_REGION: us-east-1<br>  ECR_REPOSITORY: &lt;your_ecr_repo&gt; #You don&#39;t need the full ARN, just the name<br><br>jobs:<br>  deploy:<br>    name: Deploy<br>    runs-on: ubuntu-latest<br>    environment: development<br><br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v3<br><br>      - name: Get AWS creds<br>        uses: aws-actions/configure-aws-credentials@v4.0.2<br>        with:<br>          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>          aws-region: ${{ env.AWS_REGION }}<br><br>      - name: Login to Amazon ECR<br>        id: login-ecr<br>        uses: aws-actions/amazon-ecr-login@v2<br>      - name: Build, tag, and push image to Amazon ECR<br>        id: build-image<br>        env:<br>          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}<br>          IMAGE_TAG: ${{ github.sha }}<br>        run: |<br>          docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .<br>          docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG<br>          echo &quot;image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG&quot; &gt;&gt; $GITHUB_OUTPUT</pre><p>Commit your changes to the repo, and you should see a job trigger. If you don’t, make sure GitHub actions are enabled for the repo. If it succeeds, check for a new image in ECR to confirm.</p><h3>Set up ECS</h3><p>This will be dense but I’ll walk through step-by-step for setting up an ECS cluster, service, task definition, load balancer, and target groups.</p><h4>Cluster</h4><ul><li>Navigate to the ECS service, and create a cluster. Normally I name things with a {project_name}-{environment} system, but feel free to do whatever makes sense. Choose Fargate for the infrastructure, and hit create.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qG0CMeIkk-mD1_1PqJQZg.png" /></figure><h4>Task Definition</h4><p>A task definition defines the parameters of our container environment. Here we set things like the image, resources and permissions. After creating a cluster, head over to Task Definitions on the left, and create a new task definition.</p><ul><li>For task definition family, add something unique. I chose “app” for my example.</li><li>Under Infrastructure requirements, make sure Fargate is checked.</li><li>Architecture should be Linux/x86_64</li><li>I chose a .25 vCPU and .5GB of vRAM</li><li>Task role should be none</li><li>Task Execution role should be set to “Create new Role”</li><li>Under Container 1, add the name of our container. I chose “python” since we’re running a python container. For image URI, just copy the URI from our image in ECR and paste it.</li><li>Under port mappings,set container port to 8000, Protocol TCP, Port name “python-8000-tcp” and HTTP app protocol.</li><li>Everything else can stay default, hit Create.</li></ul><h4>Service, ALB and Target Group</h4><p>Once the cluster is completed and we have a task definition, it’s time to launch some containers. Open the cluster from the ECS console, and create a new service. Think of a service as just a grouping of one or many task definitions. For Compute Options, choose “Launch type”, and choose fargate for the launch type, and latest for the platform version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ocw1pOnPlHTY4AeSH0rJ-w.png" /></figure><ul><li>Under deployment configuration, choose “service” for application type, choose our task definition family from the last step, and name the service something appropriate. For mine, I chose “web”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqFiY7r2VAGgpiFp6XX9OQ.png" /></figure><blockquote>Mind map of what’s happening: The “web” service runs the “app” task containing the “python” container. Lots of layers!</blockquote><ul><li>For networking, select the VPC you want to launch in, choose the appropriate subnets, and add a security group. <strong>It needs to have ports 80 &amp; 443 open to the world</strong>. Enable public IP.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wIfnOjlzUx7iJEby0i07A.png" /></figure><ul><li>Expand the load balancing section. For load balancer type, choose Application load balancer.</li><li>Select the radio button to create a new load balancer and give it a name.</li><li>Set the health check grace period to 60</li><li>It should automatically create an HTTP listener on port 80</li><li>Create a new target group, name it, set the protocol to HTTP and the health check to HTTP, and path to “/”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9elbqlMBBOi66NbfdcUKg.png" /></figure><p>Click “create” and see if it works! It should start a deployment with our task definition that has the python container. If everything worked, your service view should look like the screenshot below. If not, make sure the security group you chose has ports 80 and 443 open, and your VPC has an internet gateway attached. If your task is failing to launch, click the “Tasks” tab from the service page below and try viewing the logs to get an idea why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ulz2fbMm7I60HeOqO8dONg.png" /></figure><p>If you navigate to your ALB, you should be able to view the site from the ALB’s default DNS endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Gx3JAn_WWq1iJ2AWrdhfw.png" /></figure><h4>Add secrets &amp; automated deployments</h4><p>Next we’ll add our secrets and automate deploying them to our ECS service. This works by maintaining our task definition as a JSON file in our repo, and triggering a deploy when it gets modified. In the ECS service, open up our task definition’s latest version and view it as JSON. Copy it to your clipboard or download it. In your git repo, create a directory “.aws” and paste or move the container definition JSON file inside.</p><p>We’ll add a secret here, then modify our actions config.yml to add the steps for deployment. At the bottom of the config, add the following sections:</p><pre>      - name: Add new image URI<br>        id: task-def-img<br>        uses: aws-actions/amazon-ecs-render-task-definition@v1.2.0<br>        with:<br>            task-definition: ${{ env.ECS_TASK_DEFINITION }}<br>            container-name: ${{ env.CONTAINER_NAME }}<br>            image: ${{ steps.build-image.outputs.image }}<br>  <br>      - name: Deploy Amazon ECS task definition<br>        uses: aws-actions/amazon-ecs-deploy-task-definition@v1.4.11<br>        with:<br>            task-definition: ${{ steps.task-def-img.outputs.task-definition }}<br>            service: ${{ env.ECS_SERVICE }}<br>            cluster: ${{ env.ECS_CLUSTER }}<br>            wait-for-service-stability: true</pre><p>And under env, we’ll need a few more vars for ECS. Fill them out based on what names you gave for each component.</p><pre>env:<br>  AWS_REGION: us-east-1<br>  ECR_REPOSITORY: &lt;your_ecr_repo&gt;<br>  ECS_TASK_DEFINITION: .aws/app-config.json<br>  ECS_SERVICE: &lt;your_ecs_service&gt;<br>  ECS_CLUSTER: &lt;your_ecs_cluster&gt;<br>  CONTAINER_NAME: &quot;&lt;your_container_name&gt;&quot;</pre><p>You should end up with the following config:</p><pre>name: Build &amp; Deploy to ECR &amp; ECS<br><br>on:<br>  push:<br>    branches:<br>      - main<br><br>env:<br>  AWS_REGION: us-east-1<br>  ECR_REPOSITORY: &lt;your_ecr_repo&gt;<br>  ECS_TASK_DEFINITION: .aws/app-config.json<br>  ECS_SERVICE: &lt;your_ecs_service&gt;<br>  ECS_CLUSTER: &lt;your_ecs_cluster&gt;<br>  CONTAINER_NAME: &quot;&lt;your_container_name&gt;&quot;<br><br>jobs:<br>  deploy:<br>    name: Deploy<br>    runs-on: ubuntu-latest<br>    environment: development<br><br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v3<br><br>      - name: Get AWS creds<br>        uses: aws-actions/configure-aws-credentials@v4.0.2<br>        with:<br>          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>          aws-region: ${{ env.AWS_REGION }}<br><br>      - name: Login to Amazon ECR<br>        id: login-ecr<br>        uses: aws-actions/amazon-ecr-login@v2<br>      - name: Build, tag, and push image to Amazon ECR<br>        id: build-image<br>        env:<br>          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}<br>          IMAGE_TAG: ${{ github.sha }}<br>        run: |<br>          docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .<br>          docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG<br>          echo &quot;image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG&quot; &gt;&gt; $GITHUB_OUTPUT<br><br>      - name: Add new image URI<br>        id: task-def-img<br>        uses: aws-actions/amazon-ecs-render-task-definition@v1.2.0<br>        with:<br>            task-definition: ${{ env.ECS_TASK_DEFINITION }}<br>            container-name: ${{ env.CONTAINER_NAME }}<br>            image: ${{ steps.build-image.outputs.image }}<br>  <br>      - name: Deploy Amazon ECS task definition<br>        uses: aws-actions/amazon-ecs-deploy-task-definition@v1.4.11<br>        with:<br>            task-definition: ${{ steps.task-def-img.outputs.task-definition }}<br>            service: ${{ env.ECS_SERVICE }}<br>            cluster: ${{ env.ECS_CLUSTER }}<br>            wait-for-service-stability: true</pre><p>Commit the changes, and see if the workflow completes successfully. You should see all the steps that build the image, push to ECR, update the the task definition with the new image and deploy it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mb4ag6vZzmis5xYULzeMqA.png" /></figure><p>Now let’s add a non-sensitive variable to the container. Since these are committed to the repo, it’s important not to place sensitive data here such a keys or secrets. We’ll deal with secrets in the next step.</p><p>Remember our python container is looking for 3 variables, and we set each one in their corresponding location. Open up your task definition file, and add a variable in the “environment” block to match the following:</p><pre>            &quot;environment&quot;: [<br>                {<br>                    &quot;name&quot;: &quot;SECRET_FROM_ECS&quot;,<br>                    &quot;value&quot;: &quot;This is a secret from the ECS task def!&quot;<br>                }<br>            ],</pre><p>Commit the change and watch it deploy. Once it finishes, head back to your ALB url, and you should see the change live:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6tn2sfE1UVO45n-0M6cSQ.png" /></figure><p>To store environment variables such as DB creds, keys or other sensitive data, Secrets Manager is the easiest solution on AWS. You can pass them directly into the taskdef, but instead of “value” we use “valueFrom” and point it to a secret stored in SM. When the container starts, it pulls the secret from SM into its environment. Here’s how to set it up:</p><ul><li>Navigate to Secrets Manager in AWS, and click “store a new secret”.</li><li>Select “Other type of secret”.</li><li>For the key/value, our python code is looking for “SECRET_FROM_SM” so enter that as the key, and the value can be any text you want.</li></ul><blockquote>In a larger app, you can add all of your secrets under one object. Simply keep adding new rows, they can be referenced by their key in your code.</blockquote><ul><li>Click next and give the secret a name. Since one object can have multiple secrets, I like to keep the name specific to the app &amp; its environment.</li><li>Hit next, next again and store. We won’t be configuring the other options in this tutorial.</li></ul><p>Your secret should look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wJhHLfY81I-IiVXbF7_rw.png" /></figure><p>Be sure to grab the secret ARN, we’ll need to add it to the task definition config we have stored in git.</p><p>Before we go further, we need to grant the task definition access to read secrets from SM.</p><ul><li>Go to ECS &gt; Task Definitions &gt; Our task &amp; latest version, then click the shortcut for ecsTaskExecutionRole. This opens up the IAM role.</li><li>Click “Add Permissions” and create an inline policy.</li><li>Switch to the the JSON editor, and use the following:</li></ul><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ssm:GetParameters&quot;,<br>                &quot;secretsmanager:GetSecretValue&quot;,<br>                &quot;kms:Decrypt&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><ul><li>Select next, name the policy and hit create.</li></ul><p>Moving back to the task definition file in git, add a new block called “secrets”, and add our secret from SM using the ARN. Combined with the last step, it should look like this:</p><pre>            &quot;environment&quot;: [<br>                {<br>                    &quot;name&quot;: &quot;SECRET_FROM_ECS&quot;,<br>                    &quot;value&quot;: &quot;This is a secret from the ECS task def!&quot;<br>                }<br>            ],<br>            &quot;secrets&quot;: [<br>                {<br>                    &quot;name&quot;: &quot;SECRET_FROM_SM&quot;,<br>                    &quot;valueFrom&quot;: &quot;arn:aws:secretsmanager:us-east-1:xxxxxx:secret:docker-ecs-tutorial-xxxxx:SECRET_FROM_SM::&quot;<br>                }<br>            ],</pre><p>Save the file and push the changes, wait for the deployment to finish and check the webpage again to see if it worked. If it did, you should see our value from SM on the webpage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YM9TQAantEOR7PoQgsgLkw.png" /></figure><h3>Adding custom DNS, SSL &amp; www redirect.</h3><h4>SSL &amp; DNS</h4><p>Last piece of this guide is to run our deployment from a custom domain. I registered ecs-with-fargate.com for the purpose of this tutorial, but we need an SSL certificate before moving on. ACM provides free certs that renew automatically and are perfect for deployments like this.</p><ul><li>Open the Certificate Manager page, and request a certificate</li><li>Choose “Public certificate”</li><li>Enter your domain under the Domain names section, and add a wildcard version as well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qISVLomkpW7NLE_K6cdwQ.png" /></figure><ul><li>Select DNS validation, and hit request.</li><li>This takes you back to the certificates page. Refresh the page, and open up the cert we just requested.</li><li>Click on “Create records in Route 53” and accept. The validation should be pretty instant.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXOch64Y0VOIhn4AbL5n_A.png" /></figure><p>Next up, head over to Route 53, and open up the zone for our domain. Create a new A record, type ALIAS, and point it to our ALB. It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0rkqQMaVORObmytV3OLbQ.png" /></figure><h4>WWW Redirect</h4><p>Because someone is going to try to access your site with WWW in the URL, it’s important to have a redirect in place. Create an S3 bucket in the same region as all of our other services, and name it www.yourdomain.com, or in my case www.ecs-with-fargate.com.</p><p>Open up the bucket, go to properties, scroll all the way down to static website hosting and click edit. It should look like the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGR60XP2fv7wZaSmlxcHfg.png" /></figure><p>Create a new record in Route53 that points www to an alias with our s3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAFWC2b6rrcKPakwWeLAew.png" /></figure><h4>ALB Configuration</h4><p>Head over to the EC2 service, and select load balancers from the left side. Our ALB should be there, open it up.</p><ul><li>Navigate to Listeners and Rules, and select “Add listener”</li><li>Change the protocol to HTTPS, and port 443.</li><li>Routing actions should have “Forward to target group” selected, and you should see our target group in the dropdown. Select it.</li><li>Under secure listener settings, choose ACM for the certificate source, and the cert we just created from the dropdown. Select “Add” at the bottom.</li></ul><p>Because we’ll want to redirect requests to HTTPS, we need to edit the HTTP listener.</p><ul><li>Check the box next to HTTP:80, and click manage listener &gt; edit listener</li><li>For routing actions, choose redirect to URL, it should look like the screenshot below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYtVzeYULBUHHqjVqp7bUQ.png" /></figure><p>If you did everything correctly, our container should show up at our URL. Check yours, and if you don’t, double check your DNS settings and ALB settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*efob8vwvTxzFS42vuxemmw.png" /></figure><p>That’s it! This was a longer tutorial, mostly because I tried to make it as simple as possible for those not familiar with ECS or AWS.</p><p>Truth is, this job is hard. I’ve been working in this field for 10 years, and I still get my ass kicked on a daily basis. Every company is different, they have their own requirements and nuances, but it’s up to us to navigate those challenges and deliver reliable, secure and performative deployments.</p><p>Writing these tutorials is still new to me, but I welcome everyone to share their thoughts or opinions about these guides in the comments below. If you followed this guide and found it helpful, let me know!</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a93231be5dae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a static website with S3 & CloudFront, with automated deployments using GitLab Actions.]]></title>
            <link>https://medium.com/@msalisbu/deploying-a-static-website-with-s3-cloudfront-with-automated-deployments-using-gitlab-actions-f68e22aa6225?source=rss-982bed7165e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f68e22aa6225</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[cloudfront-and-s3]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Michael Salisbury]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 07:52:01 GMT</pubDate>
            <atom:updated>2025-01-05T22:13:45.680Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying a static website with S3 &amp; CloudFront, with automated deployments using GitHub Actions.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A1fsaPQCXcg6003b.jpg" /><figcaption><a href="http://msalisbu.com">msalisbu.com</a></figcaption></figure><p>CloudFront + S3 is one of the cheapest and most scalable solutions when it comes to hosting static content on the web. Having a cache like CloudFront in front of your static content means that it only has to fetch an object from S3 <em>once</em>, and will serve that object from all of its nodes across the globe. This reduces the cost of outgoing data transfers, making this an extremely cost effective approach. Below I’ll outline step by step how to set up the CloudFront distribution, S3 bucket, SSL, redirects, DNS and even some automatic deployments with GitHub Actions.</p><h3>Prerequisites &amp; assumptions</h3><p>In order for this to work, we need the following before proceeding.</p><ul><li>An AWS account with a valid payment method.</li><li>Your DNS zone (Domain) active in Route53. I’m using a domain I purchased called s3withcloudfront.com for the tutorial.</li><li>A GitHub account (for the automation), and some basic familiarity with git.</li></ul><blockquote>To make things as easy as possible, managing the DNS with Route53 in the same AWS account is crucial since we need to point the apex (root) of the domain to CloudFront via an A record type “ALIAS”, and many registrars don’t support this method. You can’t add a CNAME at the apex of a domain. If you plan on using this guide on a subdomain, you can ignore this.</blockquote><h3>Setting up AWS services</h3><p><strong>ACM/SSL</strong></p><p>First step will be to generate an SSL certificate for the CloudFront distribution to use. The benefit of ACM certs is that they’re free and renew automatically, plus you can use them across other services in AWS.</p><ol><li>Navigate to the Certificate Manager service (ACM), and ensure you’re in the us-east-1 region.</li><li>Select “request a certificate” &amp; “public certificate”.</li><li>Enter the domain name you’re going to use, and add another domain name with a wildcard subdomain (*.example.com).</li><li>Select DNS validation &amp; hit request.</li><li>On the certificates page, refresh, select the certificate you just created. In the domains section, select “Create records in Route53” . Once the DNS propagates, the certificate will be valid. Please note that ACM uses these DNS records to validate the cert and renew automatically. If you remove the records, the certificate will eventually expire.</li></ol><p><strong>S3</strong></p><p>S3 is where the files of our static website will live, and where future content changes get deployed to.</p><ol><li>Navigate to the S3 service and click “Create bucket”</li><li>Leave everything default, but change the region to east-1, and name the bucket the same as the domain you’re using.</li><li>In a text editor of your choice, type “Hello World!” and save it as index.html. Make sure it doesn’t end in txt or another extension, and then upload it to the bucket via the console.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AaCXELRbPkh3KEskjiUzhg.png" /></figure><p><strong>CloudFront</strong></p><p>A CloudFront distribution has two main concepts. The “Origin” or source of the content to be served, and the “Behaviors” which let us configure cache settings and even multiple origins based on the request path.</p><p>For example, we could have different origins for different paths. Maybe domain.com/blog goes to one bucket, and domain.com/app goes to an NLB connected to ECS. An origin doesn&#39;t necessarily need to be an S3 bucket, they can be other AWS services as well.</p><ol><li>Navigate to the CloudFront service, and click “Create distribution”.</li><li>For the origin domain, drop down the menu and select the S3 bucket we just created. The name field should automatically populate with bucketname.com.s3.us-east-1.amazonaws.com</li><li>Origin access is an important step. Because we defaulted to block all public access to the bucket, we need to grant CloudFront permission to read it. This is a more secure method than making a bucket public, buckets should always remain private.</li><li>Select “Origin access control settings” and “Create new OAC”. Add a description, then click Create.</li><li>For viewer, select Redirect HTTP to HTTPS</li><li>For WAF settings, select “Do not enable security protections” It’s unnecessary for this tutorial.</li><li>In the settings section, select only north America to reduce costs, or use all edge locations for the most performance.</li><li>For alternate domain name, enter the domain where we’re going to host the website. In my case it’s s3withcloudfront.com</li><li>Select the custom SSL certificate we created earlier from the dropdown.</li><li><strong>Default root object should be index.html</strong></li><li>Enter a description if desired, and click create!</li></ol><p>You’ll get a banner warning asking you to update the S3 policy. Click “Copy policy” on the righthand side, and navigate back to our S3 bucket we created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*La_bvYKAJW6-siE2cKdFlw.png" /></figure><p>In the bucket, select the permissions tab, scroll down to the bucket policy section, select “Edit” and paste the policy you copied from the message, then save it. Your policy should look like the following:</p><pre>{<br>    &quot;Version&quot;: &quot;2008-10-17&quot;,<br>    &quot;Id&quot;: &quot;PolicyForCloudFrontPrivateContent&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;AllowCloudFrontServicePrincipal&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;Service&quot;: &quot;cloudfront.amazonaws.com&quot;<br>            },<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::&lt;bucket name&gt;/*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;AWS:SourceArn&quot;: &quot;arn:aws:cloudfront::&lt;account ID&gt;:distribution/&lt;Distribution ID&gt;&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><blockquote>There are four main takeaways here. The Effect, action, resource and condition. We “Allow” the “Action” (s3:GetObject) to the “Resource” (the bucket ARN and it’s contents) under the “Condition” that the request is ONLY made by the CloudFront distribution. No other read access is granted otherwise.</blockquote><p><strong>DNS</strong></p><p>It’s time to announce to the internet where to find our site.</p><ol><li>Navigate to Route53, hosted zones, and select our domain.</li><li>Click Create record. Record type A, and toggle the “Alias” switch. Choose “Alias to CloudFront distribution”, and our distribution should pop up on the dropdown below. Create records.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bziNwAfG5e33MeJe-FghTg.png" /></figure><p>The propagation should be nearly instant. Try browsing your site and see if it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*eQxEimh4DAQGhqd28O4N1Q.png" /></figure><p>If it doesn’t, read through the steps again carefully. For example, if you get an error such as Access Denied, you may want to double check if the default root object is configured in the CloudFront distribution. Also ensure that the S3 bucket policy was correctly saved in the bucket settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*AxzovWEkTLEyDEEQfX6pBw.png" /></figure><p><strong>WWW?</strong></p><p>For extra points, and because someone somewhere will try to browse our site with “WWW” in the domain, we should at least set it up to redirect. Doing so is going to take another S3 bucket, but it’s simple.</p><ol><li>Head back to S3, create a bucket with the same name but with “www.” in front. No other changes needed, but make sure the region matches your other bucket.</li><li>After the bucket is created, open it and navigate to “Properties” and scroll all the way down to “Static Website Hosting” and click edit.</li><li>For static website hosting, toggle Enable. Hosting type should be “redirect requests for an object” and the host name should be the apex, s3withcloudfront.com in my case. Protocol should be https. Save changes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*WC-4rGpEXM4fyQgdvTJxcw.png" /></figure><p>4. Head back to Route53, select our zone, and add a record. Enter www for the record name, Type A, and toggle on Alias.</p><p>5. Route traffic to S3 endpoint, select the region of the bucket, and the last field should auto complete. Below is a screenshot example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRH9QRzWV66AlCGZYbZa0Q.png" /></figure><p>Congratulations, you’ve successfully deployed a static website with SSL using S3 and CloudFront as a cache.</p><p><strong>GitHub Actions — Automatically deploy changes</strong></p><p>Now that we have a working site on CloudFront and S3, it’s time to rig up some automated deployments so that we can eliminate the tedious process of deploying manually.</p><p>For GitHub to deploy changes into our AWS account, we’ll have to provide it with an AWS access key and secret key with appropriate permissions. This will require us to create a new IAM user and IAM policy. It’s best to use a separate user for this in order to limit the permissions in case the key is ever compromised.</p><p>Before continuing, take note of your CloudFront distribution’s ARN and s3 bucket name, or open them both in different tabs.</p><ol><li>Head over to the IAM service in AWS, select users and create user.</li><li>Name it something related to our project, I chose “github-svc” to indicate it’s a service account. Do not check the box to grant console access.</li><li>For permissions, select “Attach policies directly”, and “Create policy”. This opens a new window where we’ll scope the access of the user.</li><li>Under “Select a service” start typing CloudFront and select it.</li><li>For actions allowed, expand the “write” section and look for “CreateInvalidation”. Check the box next to it.</li><li>Move down to the resources section, click the “Specific” radio button and click “Add ARNs”. Paste in the full ARN of your distribution in the ARN field.</li><li>Select “Add more permissions” and search for S3.</li><li>Expand the “List” section, and check the box for “ListBucket”</li><li>Expand the “Read” section, and check the box for “GetObject”</li><li>Expand the “Write” section, and check the boxes “PutObject” and “DeleteObject”</li><li>Under resources, click “Specific” and for bucket, add your bucket name to the ARN and for object, do the same but with a /* at the end. It should look similar to the screenshot below:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUEtNfCwO-u0mm5B_FYuZQ.png" /></figure><p>12. Click next, name the policy something appropriate (github-svc-policy) and create policy. Below is what the policy should look like:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:ListBucket&quot;,<br>                &quot;s3:DeleteObject&quot;,<br>                &quot;s3:GetBucketAcl&quot;,<br>                &quot;cloudfront:CreateInvalidation&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::&lt;bucket name&gt;/*&quot;,<br>                &quot;arn:aws:s3:::&lt;bucket name&gt;&quot;,<br>                &quot;arn:aws:cloudfront::&lt;accountID&gt;:distribution/&lt;Distribution ID&gt;&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>13. Back to our user creation page, click the refresh button next to create policy, then in the search bar start typing the name of the policy we created. Select it, and click next. Then click create user.</p><p>14. In IAM, open the user we created, and navigate to the Security Credentials tab. Scroll down to Access keys, and create access key. Select “other” for the use case, and for the description write GitHub Actions or something similar. Click create, and DO NOT close the next page. We’ll need the access key and secret for the next step.</p><blockquote>You can download the keys, or save them locally. However, it’s best practice to keep the values stored in a password manager, or better yet only store them in GitHub. Never commit secrets to your codebase!</blockquote><p>15. In a separate tab, open up your GitHub repository, click settings, and on the left, click “Secrets and variables” and “Actions”.</p><p>16. Click “New repository secret”, name it AWS_ACCESS_KEY_ID and paste in the Access Key ID from step 14. Save it and create another secret, this time named AWS_SECRET_ACCESS_KEY, and paste the secret key from step. Click “add secret” once you’ve pasted it.</p><p>This can be a bit intimidating for people not familiar with dealing with secret keys, or IAM users &amp; permissions. Using my approach above will minimize the risk of leaking the secrets, and the permissions they have are scoped down extremely fine to only have access to as little as possible.</p><p>In your GitHub repo, add an index.html and create a directory “.github” with another directory “workflows” inside it. Inside the workflows directory, create a file called deploy.yml and paste the following code. You will need to change the values for the S3 bucket and CloudFront distribution ID.</p><pre>#.github/workflows/deploy.yml<br><br>name: Deploy to S3 and Invalidate CloudFront Cache<br><br>#Deploy only on commits to main<br>on:<br>  push:<br>    branches:<br>      - main<br><br>#Select a runtime for the job to run<br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    <br>    steps:<br><br>      #Check out the repo<br>      - name: Checkout repository<br>        uses: actions/checkout@v2<br><br>      #Set up the AWS login<br>      - name: Set up AWS credentials<br>        uses: aws-actions/configure-aws-credentials@v2<br>        with:<br>          #These are the secrets we added earlier. They get called during the build, so they&#39;re kept secure.<br>          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>          aws-region: us-east-1<br><br>        #Deploys the changes to S3 by overwriting the contents of the bucket with whatever is in git, and excludes the .git directory<br>      - name: Deploy to S3<br>        run: aws s3 sync . s3://&lt;your-bucket-name&gt; --delete --exclude &quot;.git/*&quot; &quot;.github/*&quot;<br><br>        #Tells cloudfront to dump the cache so the changed files get served<br>      - name: Invalidate CloudFront cache<br>        run: |<br>          aws cloudfront create-invalidation \<br>            --distribution-id &lt;your-distribution-id&gt; \<br>            --paths &quot;/*&quot;</pre><p>Once you’re done, commit your changes to git and you should see a pipeline get triggered. If it works, you should see the contents of your index.html get updated on your live site. Try changing more content around, and trigger more deployments to see your changes.</p><p>I hope you enjoyed this post! It’s my first medium article, and hopefully just the beginning of more tutorials with AWS and other DevOps content.. If you have any suggestions on formatting, flow or content, please leave a comment below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f68e22aa6225" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>