<?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 Vitalii Samarskyi on Medium]]></title>
        <description><![CDATA[Stories by Vitalii Samarskyi on Medium]]></description>
        <link>https://medium.com/@vsamarskyi?source=rss-112a78e9ad94------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*QVkL1Mkf18wK5MTTYtSckg.jpeg</url>
            <title>Stories by Vitalii Samarskyi on Medium</title>
            <link>https://medium.com/@vsamarskyi?source=rss-112a78e9ad94------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:50:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vsamarskyi/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[Host Hugo on AWS with S3 and CloudFront]]></title>
            <link>https://medium.com/@vsamarskyi/hosting-hugo-on-aws-with-s3-and-cloudfront-3bbf93a0fe21?source=rss-112a78e9ad94------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bbf93a0fe21</guid>
            <category><![CDATA[hugo]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Vitalii Samarskyi]]></dc:creator>
            <pubDate>Wed, 28 Aug 2024 12:39:26 GMT</pubDate>
            <atom:updated>2024-08-28T12:41:48.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wc5zLmXLFrVs8s2nz2AA3Q.png" /></figure><p><a href="https://gohugo.io/">Hugo</a> is a static site generator that is a great tool for creating blogs, documentation, and other types of websites. This site is also built with Hugo and hosted on AWS using S3 and CloudFront. It is a simple, fast, flexible way to host a static site. I didn’t find a good guide on how to host a Hugo site on AWS in their documentation, so I decided to write one.</p><p>In this article, we will learn how to build and deploy a Hugo site on newly created AWS S3 bucket and CloudFront distribution using AWS CDK.</p><h3>Prerequisites</h3><ul><li><a href="https://gohugo.io/getting-started/installing/">Hugo</a> installed on your machine</li><li><a href="https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_install">AWS CDK</a> already installed</li><li><a href="https://dotnet.microsoft.com/download">.NET</a> since we will use CDK in C#</li></ul><h3>Step 1: Create a new Hugo site</h3><p>I assume that that you already have a Hugo site created. If not, let’s create a dummy one for this example:</p><pre>hugo new site mysite<br>cd mysite<br><br>git init<br>git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke.git themes/ananke<br>echo &quot;theme = &#39;ananke&#39;&quot; &gt;&gt; hugo.toml<br>hugo server</pre><p>Follow the instructions on the <a href="https://gohugo.io/getting-started/quick-start/">Hugo website</a> for more details</p><h3>Step 2: Build the Hugo site</h3><p>Build the Hugo site by running the following command:</p><pre>cd mysite<br>hugo --minify --environment production</pre><p>This will create a public folder with the static site files. This is the folder we will deploy to S3.</p><h3>Step 3: Use AWS CDK to create infrastructure and deploy the site</h3><p>I have created a simple CDK project in C# that will create an S3 bucket and CloudFront distribution together with all the necessary permissions, roles and configurations. Here is what we are going to create:</p><ol><li><strong>S3 bucket</strong> for the static site files</li><li><strong>CloudFront Distribution</strong> to serve the site</li><li><strong>CloudFront Function</strong> on Viewer Request event to:</li></ol><ul><li>Rewrite URLs to support Hugo’s pretty URLs (e.g. /about/ instead of /about/index.html)</li><li>Redirect www to non-www URLs</li><li>Redirect non-trailing slash URLs to trailing slash URLs for consistency (e.g. /about to /about/)</li></ul><p>Let’s take a look at the CDK code:</p><pre>using Amazon.CDK;<br>using Amazon.CDK.AWS.CertificateManager;<br>using Amazon.CDK.AWS.CloudFront;<br>using Amazon.CDK.AWS.CloudFront.Origins;<br>using Amazon.CDK.AWS.IAM;<br>using Amazon.CDK.AWS.S3;<br>using Amazon.CDK.AWS.S3.Deployment;<br>using Constructs;<br>using System.Collections.Generic;<br>using static Amazon.CDK.AWS.CloudFront.CfnDistribution;<br>using static Amazon.CDK.AWS.CloudFront.CfnOriginAccessControl;<br><br>namespace Cdk<br>{<br>    public class HugoCdkStack : Stack<br>    {<br>        internal HugoCdkStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)<br>        {<br>            var bucketNameParam = new CfnParameter(this, &quot;BucketName&quot;, new CfnParameterProps<br>            {<br>                Type = &quot;String&quot;,<br>                Description = &quot;The name of the bucket to host the HUGO website&quot;,<br>                Default = &quot;fastfoodcoding-hugo&quot;<br>            });<br>            // uncomment the following lines to enable custom domain and ACM certificate<br>            //var domainNameParam = new CfnParameter(this, &quot;DomainName&quot;, new CfnParameterProps<br>            //{<br>            //    Type = &quot;String&quot;,<br>            //    Description = &quot;The domain name to use for the CloudFront distribution. Default is null&quot;,<br>            //});<br>            //var certificateArnParam = new CfnParameter(this, &quot;CertificateArn&quot;, new CfnParameterProps<br>            //{<br>            //    Type = &quot;String&quot;,<br>            //    Description = &quot;The ARN of the ACM certificate to use for the CloudFront distribution. Default is null&quot;,<br>            //});<br>            var s3Bucket = new Bucket(this, &quot;HugoSiteBucket&quot;, new BucketProps<br>            {<br>                BucketName = bucketNameParam.ValueAsString,<br>                RemovalPolicy = RemovalPolicy.DESTROY,<br>                BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,<br>            });<br>            var cfnOriginAccessControl = new CfnOriginAccessControl(this, &quot;OriginAccessControl&quot;, new CfnOriginAccessControlProps<br>            {<br>                OriginAccessControlConfig = new OriginAccessControlConfigProperty<br>                {<br>                    Name = &quot;HugoSiteBucket-OriginAccessControl&quot;,<br>                    OriginAccessControlOriginType = &quot;s3&quot;,<br>                    SigningBehavior = &quot;always&quot;,<br>                    SigningProtocol = &quot;sigv4&quot;<br>                }<br>            });<br>            // Hugo uses pretty URLs instead of index.html for every path<br>            // S3 or CloudFront does not support this out of the box<br>            // Let&#39;s use a CloudFront lightweight function on Viewer Request event to achieve that<br>            // As a bonus, for consistency we can redirect www to non-www and fix trailing slashes in URLs<br>            var redirectFunction = new Function(this, &quot;RedirectFunction&quot;, new FunctionProps<br>            {<br>                FunctionName = &quot;HugoSiteViewerRequestFunction&quot;,<br>                Runtime = FunctionRuntime.JS_2_0,<br>                Comment = &quot;Redirect to index.html if the request is for a directory&quot;,<br>                Code = FunctionCode.FromInline(GetFunctionCode()),<br>            });<br>            var cfnDistribution = new Distribution(this, &quot;HugoSiteDistribution&quot;, new DistributionProps<br>            {<br>                DefaultRootObject = &quot;index.html&quot;,<br>                DefaultBehavior = new BehaviorOptions<br>                {<br>                    Origin = new S3OacOrigin(s3Bucket, new S3OriginProps<br>                    {<br>                        OriginAccessIdentity = null,<br>                        ConnectionAttempts = 3,<br>                        ConnectionTimeout = Duration.Seconds(10)<br>                    }),<br>                    CachedMethods = CachedMethods.CACHE_GET_HEAD,<br>                    CachePolicy = CachePolicy.CACHING_OPTIMIZED,<br>                    ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS,<br>                    FunctionAssociations = new[]<br>                    {<br>                        new FunctionAssociation<br>                        {<br>                            EventType = FunctionEventType.VIEWER_REQUEST,<br>                            Function = redirectFunction<br>                        }<br>                    }<br>                },<br>                // uncomment the following lines to enable custom domain and ACM certificate<br>                //DomainNames = bucketNameParam.ValueAsString,<br>                //Certificate = Certificate.FromCertificateArn(this, &quot;Certificate&quot;, certificateArnParam.ValueAsString)<br>            });<br>            s3Bucket.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps<br>            {<br>                Actions = [&quot;s3:GetObject&quot;],<br>                Principals = [new ServicePrincipal(&quot;cloudfront.amazonaws.com&quot;)],<br>                Effect = Effect.ALLOW,<br>                Resources = [s3Bucket.ArnForObjects(&quot;*&quot;)],<br>                Conditions = new Dictionary&lt;string, object&gt;<br>                {<br>                    [&quot;StringEquals&quot;] = new Dictionary&lt;string, object&gt;<br>                    {<br>                        [&quot;AWS:SourceArn&quot;] = $&quot;arn:aws:cloudfront::{this.Account}:distribution/{cfnDistribution.DistributionId}&quot;<br>                    }<br>                }<br>            }));<br>            // workaround using the L1 construct to attach the OriginAccessControl to the CloudFront Distribution<br>            var l1CfnDistribution = cfnDistribution.Node.DefaultChild as CfnDistribution;<br>            l1CfnDistribution.AddPropertyOverride(&quot;DistributionConfig.Origins.0.OriginAccessControlId&quot;, cfnOriginAccessControl.AttrId);<br>            // sync our Hugo website public/ folder with the S3 bucket<br>            // don&#39;t forget to run &quot;hugo&quot; before deploying the CDK stack<br>            var _ = new BucketDeployment(this, &quot;DeployWebSite&quot;, new BucketDeploymentProps<br>            {<br>                // sync the contents of the public/ folder with the S3 bucket<br>                Sources = [Source.Asset(&quot;../mysite/public&quot;)],<br>                DestinationBucket = s3Bucket,<br>                // invalidate the cache on the CloudFront distribution when the website is updated<br>                Distribution = cfnDistribution,<br>                DistributionPaths = [&quot;/*&quot;],<br>            });<br>        }<br>        private static string GetFunctionCode()<br>        {<br>            return @&quot;<br>             async function handler(event) {<br>                const request = event.request;<br>                const host = request.headers.host.value;<br>                const uri = request.uri;<br>                if (!request.uri.endsWith(&#39;/&#39;) &amp;&amp; !request.uri.includes(&#39;.&#39;)) {<br>                    request.uri += &#39;/&#39;;<br>                    return redirectResponse(&#39;https://&#39; + host + request.uri);<br>                }<br>                if (host.startsWith(&#39;www.&#39;)) {<br>                    return redirectResponse(&#39;https://&#39; + host.replace(&#39;www.&#39;, &#39;&#39;) + request.uri);<br>                }<br>                if (uri.endsWith(&#39;/&#39;)) {<br>                    request.uri += &#39;index.html&#39;;<br>                }<br>                return request;<br>            }<br>            function redirectResponse(newurl) {<br>                return {<br>                    statusCode: 301,<br>                    statusDescription: &#39;Moved Permanently&#39;,<br>                    headers: { &#39;location&#39;: { &#39;value&#39;: newurl } }<br>                };<br>            }&quot;;<br>        }<br>    }<br>}<br>public class S3OacOrigin : OriginBase<br>{<br>    public S3OacOrigin(IBucket bucket, IOriginProps props = null) : base(bucket.BucketRegionalDomainName, props)<br>    {<br>    }<br>    // workaround to avoid the &quot;OriginAccessIdentity&quot; property to be rendered in the CloudFormation template<br>    protected override IS3OriginConfigProperty RenderS3OriginConfig()<br>    {<br>        return new S3OriginConfigProperty<br>        {<br>            OriginAccessIdentity = &quot;&quot;<br>        };<br>    }<br>}</pre><h3>Step 4: Deploy the CDK stack</h3><p>To deploy the CDK stack, simply run the following commands:</p><pre>cdk deploy --parameters BucketName=fastfoodcoding-hugo</pre><h3>Conclusion</h3><p>That’s it! You have successfully deployed a Hugo site on AWS using S3 and CloudFront. You can now access your site using the CloudFront distribution URL. You can also use a custom domain and ACM certificate by uncommenting the respective lines in the CDK code. But this requires some additional setup in Route 53 and ACM.</p><p>👉 For more coding tips and tutorials, check out <a href="https://fastfoodcoding.com/">fastfoodcoding.com</a> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bbf93a0fe21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clicky Anti-Adblock tracking on CloudFront]]></title>
            <link>https://medium.com/@vsamarskyi/clicky-anti-adblock-tracking-on-cloudfront-19c1dad1553b?source=rss-112a78e9ad94------2</link>
            <guid isPermaLink="false">https://medium.com/p/19c1dad1553b</guid>
            <category><![CDATA[clicky]]></category>
            <category><![CDATA[website-analytics]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[adblock]]></category>
            <dc:creator><![CDATA[Vitalii Samarskyi]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 23:32:15 GMT</pubDate>
            <atom:updated>2024-06-30T23:32:15.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*lBUID9jF-lmFeJDZ" /></figure><p>If you have a website hosted on AWS S3/CloudFront and use <a href="https://clicky.com/">Clicky</a> for analytics, you might face issues with Adblockers and browsers blocking Clicky’s tracking code. To bypass this, Clicky offers an <a href="https://clicky.com/help/proxy">Adblock/Proxy</a> solution, which involves proxying the tracking code through your own domain to disguise it.</p><p>Usually, this requires modifying the configuration of servers like Nginx, Apache, or Caddy. However, since our website is a static site hosted on AWS S3 behind CloudFront, we need a different solution.</p><blockquote>Based on a true story and implemented on <a href="https://fastfoodcoding.com/"><strong>_fastFoodCoding | Coding recipes for developers</strong></a><strong>.</strong> Go and check out by yourself.</blockquote><h3>Assumptions</h3><ul><li>You have a website hosted on AWS S3 behind the CloudFront.</li><li>You have a Clicky account.</li></ul><h3>Preparation</h3><p>First, open the instructions on the <a href="https://clicky.com/stats/prefs-tracking-code">Prefs » Tracking Code</a> page. We are interested in the <strong>Anti-adblock tracking code (for advanced users)</strong> section. You will see the values for Javascript path and Beacon path that you need to use on your website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*JCNnzetBZVTmB88H" /><figcaption>Example of Clicky settings for Anti-adblock tracking code</figcaption></figure><p>Let’s configure reverse proxy from our website to Clicky servers. We will use the example for nginx as a guide.</p><pre>http {<br>	server {<br>		### COPY THE CODE BELOW INTO YOUR WEBSITE&#39;S EXISTING SERVER{} (VIRTUAL HOST) BLOCK<br>		### CLICKY ANTI-ADBLOCK PROXY - https://clicky.com/help/proxy<br>		<br>		# IMPORTANT NOTE: Incoming X-Forwarded-For headers are supported by default.<br>		# To disable this, replace all &quot;$proxy_add_x_forwarded_for&quot; references with &quot;$remote_addr&quot;.<br>		<br>		# DNS RESOLVER - if already defined elsewhere, this can optionally be deleted.<br>		resolver 1.1.1.1;<br>		<br>		# COOKIES - override cookie header to just send the service-related first party cookies.<br>		set $cookie &quot;&quot;;<br>		if ($cookie__cky_ignore) {<br>			set $cookie &quot;_cky_ignore=$cookie__cky_ignore; _cky_osa=$cookie__cky_osa&quot;;<br>		}<br>		<br>		# JAVASCRIPT TRACKING CODE<br>		location = /d63e7f9a80329d6.js {<br>			proxy_pass https://static.getclicky.com/js?in=%2F67c5f93e3b0915a;<br>			proxy_connect_timeout 10s;<br>			proxy_http_version 1.1;<br>			proxy_ssl_server_name on;<br>			proxy_set_header Host static.getclicky.com;<br>			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>			proxy_set_header Cookie &quot;&quot;;<br>		}<br>		<br>		# JAVASCRIPT BEACON<br>		location = /67c5f93e3b0915a {<br>			proxy_pass https://in.getclicky.com/in.php;<br>			proxy_connect_timeout 10s;<br>			proxy_http_version 1.1;<br>			proxy_ssl_server_name on;<br>			proxy_set_header Host in.getclicky.com;<br>			proxy_set_header X-Forwarded-Proto $scheme;<br>			proxy_set_header X-Forwarded-Host  $host;<br>			proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;<br>			proxy_set_header Cookie $cookie;<br>		}<br>		<br>		### / CLICKY <br>	}<br>}</pre><p>We are interested in the following:</p><ol><li>proxy_pass https://static.getclicky.com/js?in=%2F67c5f93e3b0915a; - Javascript path.</li><li>proxy_pass https://in.getclicky.com/in.php; - Beacon path.</li><li>All cookies except _cky_ignore and _cky_osa are filtered.</li><li>There are some manipulations with headers.</li></ol><h3>Solution</h3><p>To begin, let’s create two new Origins in the settings of our CloudFront distribution:</p><p>For Javascript path:</p><ul><li><strong>Origin Domain Name</strong>: static.getclicky.com</li><li><strong>Protocol</strong>: HTTPS Only</li><li><strong>Minimum Origin SSL Protocol</strong>: TLSv1.2</li></ul><p>For Beacon path:</p><ul><li><strong>Origin Domain Name</strong>: in.getclicky.com</li><li><strong>Protocol</strong>: HTTPS Only</li><li><strong>Minimum Origin SSL Protocol</strong>: TLSv1.2</li></ul><p>Great, now we can use these Origins to configure the behavior of our CloudFront distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APakSNLz5dzTy31I3DB-Ig.png" /><figcaption>Example of Origins settings for CloudFront</figcaption></figure><p>Now let’s configure the behavior of our CloudFront distribution.</p><h4>For Javascript path:</h4><ul><li><strong>Path Pattern</strong>: /d63e7f9a80329d6.js (replace with your Javascript path)</li><li><strong>Origin or Origin Group</strong>: static.getclicky.com</li><li><strong>Viewer Protocol Policy</strong>: HTTPS only</li><li><strong>Allowed HTTP Methods</strong>: GET, HEAD</li><li><strong>Cache Policy</strong>: Managed-CachingDisabled</li><li><strong>Origin Request Policy</strong>: Create a new Origin Request Policy</li><li><strong>Name</strong>: FastfoodCoding_Clicky_js (choose any convenient name)</li><li><strong>Headers</strong>: All viewer headers except Host</li><li><strong>Cookies</strong>: Include the following cookies _cky_ignore, _cky_osa</li><li><strong>Query Strings</strong>: All</li></ul><h4>For Beacon path:</h4><ul><li><strong>Path Pattern</strong>: /67c5f93e3b0915a (replace with your Beacon path)</li><li><strong>Origin or Origin Group</strong>: in.getclicky.com</li><li><strong>Viewer Protocol Policy</strong>: HTTPS only</li><li><strong>Allowed HTTP Methods</strong>: GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE</li><li><strong>Cache Policy</strong>: Managed-CachingDisabled</li><li><strong>Origin Request Policy</strong>: FastfoodCoding_Clicky_js (created in the previous step)</li></ul><p>Wow, we have configured the behavior for our CloudFront distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGpX0ec-Ao2PocB499r53g.png" /><figcaption>Example of Behaviors settings CloudFront</figcaption></figure><p>The last step remains — correctly construct paths to the Clicky servers. To do this, we’ll create a CloudFront Function that will trigger on Viewer Request. Choose Runtime: cloudfront-js-2.0 and write the following code:</p><pre>function handler(event) {<br><br>    if (event.request.uri === &#39;/d63e7f9a80329d6.js&#39;) {<br>        event.request.uri = &#39;/js&#39;<br>        event.request.querystring = &#39;in=%2F67c5f93e3b0915a&#39;<br>    } else if (event.request.uri === &#39;/67c5f93e3b0915a&#39;) {<br>        event.request.uri = &#39;/in.php&#39;<br>    }<br><br>    return event.request;<br>}</pre><p>Now, for each request to /d63e7f9a80329d6.js, we will redirect to /js?in=%2F67c5f93e3b0915a, and for /67c5f93e3b0915a, to /in.php.</p><p>That’s it! All that’s left is to connect our CloudFront Function to the behaviors of our distribution, and you’re good to go. Just add the following code snippet to your site:</p><pre>&lt;script async data-id=&quot;101449625&quot; src=&quot;/d63e7f9a80329d6.js&quot;&gt;&lt;/script&gt;</pre><p>Well done!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19c1dad1553b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Hugo with AWS CodeBuild on Lambda Compute]]></title>
            <link>https://medium.com/@vsamarskyi/deploying-hugo-with-aws-codebuild-on-lambda-compute-83d2c6a54770?source=rss-112a78e9ad94------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d2c6a54770</guid>
            <category><![CDATA[hugo]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[codebuild]]></category>
            <dc:creator><![CDATA[Vitalii Samarskyi]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 21:09:20 GMT</pubDate>
            <atom:updated>2024-06-30T16:53:47.801Z</atom:updated>
            <content:encoded><![CDATA[<p>Build smaller, faster, cheaper, EC2 free</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zLdY6Fsgy9ZURsEJEGAig.png" /></figure><h3>Introduction</h3><p>In this simple guide, we will review how to deploy a Hugo static site using AWS CodeBuild <strong>on AWS Lambda compute </strong>instead of traditional EC2. AWS Lambda compute offers optimized start-up speeds and automatic scaling for faster builds. However, there are some limitations to consider.</p><p>We will use AWS CodeBuild to <strong>build the Hugo site</strong>, <strong>deploy it to an S3 bucket</strong>, and <strong>invalidate the CloudFront cache</strong>. GitHub will be used as the source repository for the Hugo site.</p><h3>Pre-requisites</h3><p>Before we start, make sure you have the following:</p><ul><li>Your Hugo site source code on GitHub;</li><li>Your Hugo site is already hosted on AWS S3 and CloudFront. If not, follow the <a href="https://fastfoodcoding.com/recipes/hugo/hosting-hugo-on-aws-s3-cloudfront/">Hosting Hugo on AWS S3 and CloudFront</a> recipe to set it up.</li></ul><h3>Step 1: Create a new IAM role for CodeBuild project</h3><p>We need to create a new IAM role that will be used by the CodeBuild project to sync the S3 bucket and invalidate CloudFront distribution.</p><h4>Create a new policy</h4><ol><li>Go to the <a href="https://us-east-1.console.aws.amazon.com/iam/home#/policies">AWS IAM console: Policies</a>.</li><li>Click on the Create policy button.</li><li>Click on the JSON tab and paste the following policy document:</li></ol><blockquote><strong><em>💡Please note: </em></strong><em>Replace </em><em>YOUR_BUCKET_NAME, </em><em>YOUR_ACCOUNT_ID, and </em><em>YOUR_DISTRIBUTION_ID with your values.</em></blockquote><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:DeleteObject&quot;,<br>                &quot;s3:GetBucketAcl&quot;,<br>                &quot;s3:GetBucketLocation&quot;,<br>                &quot;s3:ListBucket&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::YOUR_BUCKET_NAME&quot;,<br>                &quot;arn:aws:s3:::YOUR_BUCKET_NAME/*&quot;<br>            ]<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;cloudfront:CreateInvalidation&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:cloudfront::YOUR_ACCOUNT_ID:distribution/YOUR_DISTRIBUTION_ID&quot; <br>            ]<br>        }<br>    ]<br>}</pre><p>4. Click on the Next button.<br>5. Fill in the policy name and description.<br>6. Click on the Create policy button.</p><h4>Create a new role</h4><ol><li>Go back to the <a href="https://console.aws.amazon.com/iam/home#/roles">AWS IAM console: Roles</a>.</li><li>Click on the Create Role button.</li><li>Select AWS service as the trusted entity.</li><li>Choose CodeBuild as the service that will use this role.</li><li>Click on the Next: Add Permissions button.</li><li><strong>Search and check the checkbox next to the policy you created previously.</strong></li><li>Click on the Next: Name, review and create button.</li><li>Fill in the role name and description.</li><li>Click on the Create role button.</li></ol><p>Now you have a new IAM role that can be used by the CodeBuild project.</p><h3>Step 2: Create a new CodeBuild project</h3><p>Let’s create a new CodeBuild project that will build and deploy our site on every push to the GitHub repository.</p><p>Go to the <a href="https://console.aws.amazon.com/codesuite/codebuild/projects">AWS CodeBuild console</a> and click on the Create build project button.</p><h4>Project configuration</h4><ol><li>Fill in the project name and description.</li><li>Restrict number of concurrent builds this project can start to 1.</li></ol><h4>Source</h4><ol><li>Select GitHub as the source provider.</li><li>Click on the Connect to GitHub button and authorize AWS to access your GitHub repositories.</li><li>Select your repository and branch.</li></ol><h4>Environment</h4><ol><li>Select Managed Image as the environment image.</li><li>Choose Lambda as the compute type.</li><li>Operating system: Amazon Linux (you don’t have other options here).</li><li>Runtime: Golang.</li><li>Image: aws/codebuild/amazonlinux-aarch64-lambda-standard:go1.21 or most recent.</li><li>Image version: Always use the latest image for this runtime version.</li><li>Service role: Existing service role.</li><li><strong>Role ARN: choose the role you created in the previous step.</strong></li><li>Check the Allow AWS CodeBuild to modify this service role so it can be used with this build project checkbox.</li></ol><h4>Buildspec</h4><p>Choose Insert build commands and paste the following buildspec:</p><blockquote><em>⚠️CodeBuild Lambda environment is limited and does not allow the use of package managers like </em><em>yum or </em><em>rpm since they require root access. Therefore, </em><strong><em>we need to manually download and extract Hugo during the build</em></strong><em>. For more information, refer to the </em><a href="https://docs.aws.amazon.com/codebuild/latest/userguide/lambda.html#lambda.limitations"><em>Limitations of AWS Lambda compute</em></a><em>.</em></blockquote><blockquote><em>💡Replace </em><em>YOUR_BUCKET_NAME, </em><em>YOUR_REGION, and </em><em>YOUR_DISTRIBUTION_ID with your values.</em></blockquote><pre>version: 0.2<br><br>phases:<br>  install:<br>    commands:<br>      # Download and extract Hugo<br>      - curl -Ls https://github.com/gohugoio/hugo/releases/download/v0.127.0/hugo_extended_0.127.0_linux-arm64.tar.gz -o /tmp/hugo.tar.gz<br>      - mkdir /tmp/hugo_0.127.0<br>      - tar xf /tmp/hugo.tar.gz -C /tmp/hugo_0.127.0<br>      - /tmp/hugo_0.127.0/hugo version<br>  build:<br>    commands:<br>      # Build the site using Hugo<br>      - /tmp/hugo_0.127.0/hugo --minify --gc<br>  post_build:<br>    commands:<br>      # Sync the Hugo build public folder with S3 bucket<br>      - aws s3 sync public/ s3://YOUR_BUCKET_NAME --region YOUR_REGION --delete<br>      # Invalidate CloudFront cache<br>      - aws cloudfront create-invalidation --distribution-id YOUR_DISTRIBUTION_ID --paths &#39;/*&#39;</pre><h4>Artifacts</h4><p>Select No artifacts as the output artifact type since we are deploying the site to S3 withing the buildspec.</p><h4>Logs</h4><p>Optionally, you can configure CloudWatch logs for the build project. This will help you debug the build process.</p><h3>Step 3: Trigger the build</h3><p>Now you can trigger the build by pushing a new commit to the GitHub repository. The CodeBuild project will automatically start the build process and deploy the site to the S3 bucket. Alternatively, you can manually start the build pressing the Start build button in the CodeBuild console.</p><p><strong>That’s it! You have successfully deployed your Hugo site using AWS CodeBuild on a Lambda environment.</strong></p><h3>Bonus: CloudFormation deployment</h3><p>If you prefer to deploy the CodeBuild project using CloudFormation, you can use the template below. It is parametrized with the required values.</p><blockquote><em>⚠️Consider to setup the GitHub connection manually in the AWS CodeBuild console before deploying the CloudFormation stack.</em></blockquote><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Description: CodeBuild project for Hugo site deployment<br>Parameters:<br>  ProjectName:<br>    Type: String<br>    Description: CodeBuild project name<br>    Default: HugoSiteBuild<br>  SiteBucketName:<br>    Type: String<br>    Description: Site S3 bucket name<br>  DistributionId:<br>    Type: String<br>    Description: CloudFront distribution ID<br>  Region:<br>    Type: String<br>    Description: AWS region<br>  HugoVersion:<br>    Type: String<br>    Description: Hugo version<br>    Default: 0.127.0<br>  GitHubRepo:<br>    Type: String<br>    Description: GitHub repository URL<br>Resources:<br>  ServiceRole:<br>    Type: AWS::IAM::Role<br>    Properties:<br>      AssumeRolePolicyDocument:<br>        Version: &#39;2012-10-17&#39;<br>        Statement:<br>          - Effect: Allow<br>            Principal:<br>              Service: codebuild.amazonaws.com<br>            Action: sts:AssumeRole<br>      Policies:<br>        - PolicyName: CodeBuildServiceRolePolicy<br>          PolicyDocument:<br>            Version: &#39;2012-10-17&#39;<br>            Statement:<br>              - Effect: Allow<br>                Action:<br>                  - logs:CreateLogGroup<br>                  - logs:CreateLogStream<br>                  - logs:PutLogEvents<br>                Resource:<br>                  - !Sub arn:aws:logs:${Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}<br>                  - !Sub arn:aws:logs:${Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ProjectName}:*<br>        - PolicyName: DeploySiteCodeBuildPolicy<br>          PolicyDocument:<br>            Version: &#39;2012-10-17&#39;<br>            Statement:<br>              - Effect: Allow<br>                Action:<br>                  - s3:PutObject<br>                  - s3:GetObject<br>                  - s3:DeleteObject<br>                  - s3:GetBucketAcl<br>                  - s3:GetBucketLocation<br>                  - s3:ListBucket<br>                Resource:<br>                  - !Sub arn:aws:s3:::${SiteBucketName}<br>                  - !Sub arn:aws:s3:::${SiteBucketName}/*<br>              - Effect: Allow<br>                Action:<br>                  - cloudfront:CreateInvalidation<br>                Resource:<br>                  - !Sub arn:aws:cloudfront::${AWS::AccountId}:distribution/${DistributionId}<br>  CodeBuildProject:<br>    Type: AWS::CodeBuild::Project<br>    Properties:<br>      Name: !Ref ProjectName<br>      Description: Build and deploy Hugo site<br>      ConcurrentBuildLimit: 1<br>      Environment:<br>        Type: ARM_LAMBDA_CONTAINER<br>        ComputeType: BUILD_LAMBDA_1GB<br>        Image: aws/codebuild/amazonlinux-aarch64-lambda-standard:go1.21<br>      ServiceRole: !GetAtt ServiceRole.Arn<br>      Source:<br>        Type: GITHUB<br>        BuildSpec: !Sub |<br>          version: 0.2<br>          phases:<br>            install:<br>              commands:<br>                - curl -Ls https://github.com/gohugoio/hugo/releases/download/v${HugoVersion}/hugo_extended_${HugoVersion}_linux-arm64.tar.gz -o /tmp/hugo.tar.gz<br>                - mkdir /tmp/hugo_${HugoVersion}<br>                - tar xf /tmp/hugo.tar.gz -C /tmp/hugo_${HugoVersion}<br>                - /tmp/hugo_${HugoVersion}/hugo version<br>            build:<br>              commands:<br>                - /tmp/hugo_${HugoVersion}/hugo --minify --gc<br>            post_build:<br>              commands:<br>                - aws s3 sync public/ s3://${SiteBucketName} --region us-east-1 --delete<br>                - aws cloudfront create-invalidation --distribution-id ${DistributionId} --paths &#39;/*&#39;<br>        Location: !Ref GitHubRepo<br>      Artifacts:<br>        Type: NO_ARTIFACTS<br>      Triggers:<br>        Webhook: true<br>        BuildType: BUILD<br>        FilterGroups:<br>          - - Type: EVENT<br>              Pattern: PUSH<br>      LogsConfig:<br>        CloudWatchLogs:<br>          Status: ENABLED<br>          GroupName: !Sub /aws/codebuild/${ProjectName}</pre><h3>Conclusion</h3><p>In this recipe, we learned how to deploy a GitHub sourced Hugo static site using AWS CodeBuild on a Lambda environment which is a cost-effective, easier and faster way compared to the traditional EC2 environment. We also scripted all the steps in a CloudFormation template for easy deployment and management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d2c6a54770" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>