<?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 Theara Seng on Medium]]></title>
        <description><![CDATA[Stories by Theara Seng on Medium]]></description>
        <link>https://medium.com/@thearaseng?source=rss-6c76875b9810------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_iF2akJT4Ub1Vl9UZXw7-Q.jpeg</url>
            <title>Stories by Theara Seng on Medium</title>
            <link>https://medium.com/@thearaseng?source=rss-6c76875b9810------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 22:55:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thearaseng/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[Building a Full-Stack Product App with React, Spring Boot, and Docker Compose]]></title>
            <link>https://medium.com/@thearaseng/building-a-full-stack-product-app-with-react-spring-boot-and-docker-compose-64a47f4a1080?source=rss-6c76875b9810------2</link>
            <guid isPermaLink="false">https://medium.com/p/64a47f4a1080</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Theara Seng]]></dc:creator>
            <pubDate>Fri, 27 Oct 2023 22:16:52 GMT</pubDate>
            <atom:updated>2023-10-27T22:45:21.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*SMyNTNDJfhisbPicNn8_Wg.png" /></figure><p>In this blog, I am going to share with you a very simple product app that uses React, Spring Boot, and MySQL as the frontend, backend, and database, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OFnXQBpOqBc5hdwo880sg.png" /><figcaption>Index page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xaa4GDWSSkA43mjA8_WHqA.png" /><figcaption>Product detail page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMEUy98uKeMiZhNBoqFtRg.png" /><figcaption>Product Edit page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tC3jkjdyROY-KnZQoP_Vg.png" /><figcaption>Add Product page</figcaption></figure><p>In React JS, we utilize React Context to share the state from a parent component to its child components. We also enhance it with Bootstrap to give it a more appealing appearance. These are main libraries that we use to build the React app.</p><ul><li>react-router-dom: Used to build a single-page app that enables users to browse through different pages in the app without reloading the entire application.</li><li>axios: Used to make API calls to the backend for creating, reading, updating, and deleting products.</li><li>react context: To share the app state from the parent component to its child components.</li></ul><p>ProductContext.js</p><pre>import React, { createContext, useState } from &#39;react&#39;;<br><br>export const ProductContext = createContext();<br><br>export const ProductListProvider = ({ children }) =&gt; {<br>  const [products, setProducts] = useState([]);<br>  const [product, setProduct] = useState({});<br><br>  const updateProducts = (products) =&gt; {<br>    setProducts(products)<br>  }<br><br>  const addProduct = (product) =&gt; {<br>    setProducts([... products, product]);<br>  }<br><br>  const updateProduct = (product) =&gt; {<br>    setProduct(product);<br>  }<br><br>  const removeProductById = (id) =&gt; {<br>    const newProducts = products.filter((product) =&gt; product.id !== id);<br>    setProducts(newProducts);<br>  }<br><br>  return (<br>    &lt;ProductContext.Provider value={{ products, product, updateProducts, updateProduct, removeProductById, addProduct }}&gt;<br>      {children}<br>    &lt;/ProductContext.Provider&gt;<br>  );<br>}</pre><p>ApiService.js</p><pre>import axios from &quot;axios&quot;;<br><br>const baseURL = process.env.REACT_APP_API_BASE_URL;<br><br>const apiUrl = `${baseURL}/api/products`;<br><br>export const getProducts = async () =&gt; {<br>  try {<br>    const response = await axios.get(apiUrl);<br>    return response.data;<br>  } catch (error) {<br>    throw error;<br>  }<br>}<br><br>export const createProduct = async (product) =&gt; {<br>  try {<br>    const response = await axios.post(apiUrl, product);<br>    return response.data;<br>  } catch (error) {<br>    throw error;<br>  }<br>}<br><br>export const getProductById = async (id) =&gt; {<br>  try {<br>    const response = await axios.get(`${apiUrl}/${id}`);<br>    return response.data;<br>  } catch (error) {<br>    throw error;<br>  }<br>}<br><br>export const updateProductById = async (id, product) =&gt; {<br>  try {<br>    const response = await axios.put(`${apiUrl}/${id}`, product);<br>    return response.data;<br>  } catch (error) {<br>    throw error;<br>  }<br>}<br><br>export const deleteProductById = async (id) =&gt; {<br>  try {<br>    const response = await axios.delete(`${apiUrl}/${id}`);<br>    return response.data;<br>  } catch (error) {<br>    throw error;<br>  }<br>}</pre><p>Dockerfile</p><pre># Build stage<br>FROM node:18 AS build<br><br>WORKDIR /app<br><br># Copy package.json and package-lock.json to the container<br>COPY package*.json ./<br><br># Install dependencies<br>RUN npm install<br><br># Copy the rest of the application code<br>COPY . .<br><br># Build the React app<br>RUN npm run build<br><br># Serve stage<br>FROM nginx:1.25.1<br><br># Copy the custom nginx.conf file to the container<br>COPY .docker/nginx.conf /etc/nginx/nginx.conf<br><br># Copy the built React app from the build stage to the nginx container<br>COPY --from=build /app/build /usr/share/nginx/html<br><br># Expose port 80<br>EXPOSE 80<br><br># Start Nginx<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>In the backend part, we implement CRUD APIs using a simple Spring Boot web application and manipulate MySQL data through Spring Data JPA.</p><p>ProductController.java</p><pre>package com.example.backend.controller;<br><br>import com.example.backend.model.Product;<br>import com.example.backend.service.ProductService;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.web.bind.annotation.*;<br><br>import java.util.List;<br><br>@RestController<br>@RequestMapping(&quot;/api/products&quot;)<br>public class ProductController {<br><br>    @Autowired<br>    private ProductService productService;<br><br>    @PostMapping<br>    public Product save(@RequestBody Product product) {<br>        return productService.save(product);<br>    }<br><br>    @PutMapping(&quot;/{id}&quot;)<br>    public Product update(@PathVariable Long id, @RequestBody Product product) {<br>        return productService.updateById(id, product);<br>    }<br><br>    @GetMapping<br>    public List&lt;Product&gt; findAll() {<br>        return productService.findAll();<br>    }<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public Product findById(@PathVariable Long id) {<br>        return productService.findById(id);<br>    }<br><br>    @DeleteMapping(&quot;/{id}&quot;)<br>    @ResponseStatus(HttpStatus.NO_CONTENT)<br>    public void deleteById(@PathVariable Long id) {<br>        productService.deleteById(id);<br>    }<br><br>}</pre><p>ProductServiceImpl.java</p><pre>package com.example.backend.service.impl;<br><br>import com.example.backend.model.Product;<br>import com.example.backend.repository.ProductRepository;<br>import com.example.backend.service.ProductService;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br><br>import java.util.List;<br><br>@Service<br>public class ProductServiceImpl implements ProductService {<br><br>    @Autowired<br>    private ProductRepository productRepository;<br><br>    @Override<br>    public Product save(Product product) {<br>        return productRepository.save(product);<br>    }<br><br>    @Override<br>    public Product updateById(Long id, Product product) {<br><br>        Product managedProduct = this.findById(id);<br>        managedProduct.setTitle(product.getTitle());<br>        managedProduct.setQuantity(product.getQuantity());<br>        managedProduct.setPrice(product.getPrice());<br><br>        return this.save(managedProduct);<br>    }<br><br>    @Override<br>    public List&lt;Product&gt; findAll() {<br>        return productRepository.findAll();<br>    }<br><br>    @Override<br>    public Product findById(Long id) {<br>        return productRepository.findById(id).orElse(null);<br>    }<br><br>    @Override<br>    public void deleteById(Long id) {<br>        productRepository.deleteById(id);<br>    }<br><br>}</pre><p>We also insert two products when the Spring Boot starts in MyCommandLineRunner.java</p><pre>package com.example.backend;<br><br>import com.example.backend.model.Product;<br>import com.example.backend.service.ProductService;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.CommandLineRunner;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class MyCommandLineRunner implements CommandLineRunner {<br><br>    @Autowired<br>    private ProductService productService;<br><br>    @Override<br>    public void run(String... args) throws Exception {<br>        Product product = new Product();<br>        product.setTitle(&quot;iPhone&quot;);<br>        product.setPrice(1200D);<br>        product.setQuantity(99);<br>        productService.save(product);<br><br>        Product product2 = new Product();<br>        product2.setTitle(&quot;Blackberry&quot;);<br>        product2.setPrice(1100D);<br>        product2.setQuantity(55);<br>        productService.save(product2);<br>    }<br>}</pre><p>In the application.properties file, we defined three environment variables: SPRING_DATASOURCE_URL, SPRING_DATASOURCE_USERNAME, and SPRING_DATASOURCE_PASSWORD</p><pre>spring.datasource.url=${SPRING_DATASOURCE_URL}<br>spring.datasource.username=${SPRING_DATASOURCE_USERNAME}<br>spring.datasource.password=${SPRING_DATASOURCE_PASSWORD}<br>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<br><br>spring.jpa.show-sql=true<br>spring.jpa.hibernate.ddl-auto=create-drop</pre><p>Dockerfile</p><pre># Use the official Maven image as the base image<br>FROM maven:3.8.4-openjdk-17 AS build<br><br># Set the working directory<br>WORKDIR /app<br><br># Copy the pom.xml and any other necessary configuration files<br>COPY ./pom.xml /app<br>COPY ./src /app/src<br><br># Build the application<br>RUN mvn clean package -Dmaven.test.skip=true<br><br># Create a new image for running the application<br>FROM openjdk:17-jdk<br><br># Set the working directory<br>WORKDIR /app<br><br># Copy the built JAR file from the previous stage<br>COPY --from=build /app/target/*.jar app.jar<br><br># Expose the port on which the Spring Boot application will run<br>EXPOSE 8080<br><br># Command to run the application<br>CMD [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p>Last but not least, we create a Docker Compose file that builds Docker images for the React App and Spring Boot App, and runs MySQL containers for testing in browsers.</p><p>docker-compose.yml</p><pre>version: &#39;3&#39;<br>services:<br>  mysql:<br>    image: mysql:8.0<br>    ports:<br>      - &quot;3306:3306&quot;<br>    environment:<br>      MYSQL_ROOT_PASSWORD: P@ssw0rd<br>      MYSQL_USER: product_user<br>      MYSQL_PASSWORD: product_user_password<br>      MYSQL_DATABASE: product<br><br>  spring-boot-app:<br>      build:<br>        context: ./backend<br>        dockerfile: Dockerfile<br>      ports:<br>        - &quot;8080:8080&quot;<br>      depends_on:<br>        - mysql<br>      environment:<br>        SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/product<br>        SPRING_DATASOURCE_USERNAME: product_user<br>        SPRING_DATASOURCE_PASSWORD: product_user_password<br><br>  react-app:<br>      build:<br>        context: ./frontend<br>        dockerfile: Dockerfile<br>      ports:<br>        - &quot;3000:80&quot;</pre><p>To run the Product App, simply execute the ‘docker-compose up’ command.</p><pre>docker-compose up --build -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0-fFhb7mrDYi2tnquF75w.png" /></figure><p>Voilà</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OFnXQBpOqBc5hdwo880sg.png" /><figcaption>Index page</figcaption></figure><h3>Source Code</h3><p>You can find the complete source code on my Github Repo.</p><p><a href="https://github.com/thearaseng/react-product-app">https://github.com/thearaseng/react-product-app</a></p><h3>A Cup of Coffee</h3><p>Thank you for reading, and if you find value in what I write, I would greatly appreciate it if you would consider buying me a coffee.</p><p>Or please consider following me on Medium <a href="https://medium.com/@thearaseng">https://medium.com/@thearaseng</a></p><p><em>As someone who blogs, it would mean a lot to me.</em></p><figure><a href="https://www.buymeacoffee.com/thearaseng"><img alt="https://www.buymeacoffee.com/thearaseng" src="https://cdn-images-1.medium.com/max/545/1*jx-d_b9LYbH0ThmH-pxx1Q.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64a47f4a1080" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Jenkins AMI using Packer]]></title>
            <link>https://medium.com/@thearaseng/build-jenkins-ami-using-packer-7ead12f25a51?source=rss-6c76875b9810------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ead12f25a51</guid>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[hashicorp-packer]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Theara Seng]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 04:07:18 GMT</pubDate>
            <atom:updated>2023-10-10T04:33:39.866Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, I aim to demonstrate how to create a Jenkins server image using Packer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5SkdGWUlv3vhryU_fUqlyQ.png" /></figure><h4>What is Packer?</h4><p>Packer is a tools to build immutable server images. Packer is particularly popular for creating Amazon Machine Images (AMIs) for AWS, but it supports many other platforms as well, including VMware, VirtualBox, Azure, Google Cloud, and more.</p><h4>Prerequisite</h4><p><strong>AWS Account:</strong> As we are going to build an Amazon AMI, we will need an AWS account.</p><p><strong>AWS Access Key:</strong> You also need to generate AWS access keys and secret keys to grant Packer permission for creating AMI images on your AWS account.</p><p><strong>Packer CLI:</strong> For sure, we will need Packer CLI installed. You can follow this page for instructions on how to install Packer CLI on your operating system. <a href="https://developer.hashicorp.com/packer/downloads">https://developer.hashicorp.com/packer/downloads</a></p><p>In this demonstration, we are going to create three files.</p><ul><li><strong>template.json:</strong> It’s the template file that defines the process of creating a machine image.</li><li><strong>script.sh:</strong> A bash script file used to install Java and the Jenkins service itself</li><li><strong>vars.json:</strong> A JSON file that stores variables, including AWS access key and secret key</li></ul><p><strong>template.json</strong></p><pre>{<br>  &quot;variables&quot;: {<br>    &quot;region&quot;: &quot;us-east-1&quot;,<br>    &quot;source_ami&quot;: &quot;ami-053b0d53c279acc90&quot;,<br>    &quot;instance_type&quot;: &quot;t2.small&quot;<br>  },<br>  &quot;builders&quot;: [<br>    {<br>      &quot;type&quot;: &quot;amazon-ebs&quot;,<br>      &quot;region&quot;: &quot;{{user `region`}}&quot;,<br>      &quot;source_ami&quot;: &quot;{{user `source_ami`}}&quot;,<br>      &quot;access_key&quot;: &quot;{{user `aws_access_key`}}&quot;,<br>      &quot;secret_key&quot;: &quot;{{user `aws_secret_key`}}&quot;,<br>      &quot;instance_type&quot;: &quot;{{user `instance_type`}}&quot;,<br>      &quot;ssh_username&quot;: &quot;{{user `ssh_username`}}&quot;,<br>      &quot;ami_name&quot;: &quot;jenkins-{{timestamp}}&quot;,<br>      &quot;tags&quot;:{<br>        &quot;Name&quot;: &quot;Jenkins - {{timestamp}}&quot;<br>      }<br>    }<br>  ],<br>  &quot;provisioners&quot;: [<br>    {<br>      &quot;type&quot;: &quot;shell&quot;,<br>      &quot;script&quot;: &quot;script.sh&quot;<br>    }<br>  ]<br>}</pre><p>We’re going to use the Ubuntu AMI in the us-east-1 region with a t2.small EC2 instance type. You can make changes to ami_id, region, and instance_type as needed.</p><p><strong>script.sh</strong></p><pre>#!/bin/bash<br><br>sudo apt-get update -y<br>sudo apt-get install openjdk-11-jdk -y<br>curl -fsSL https://pkg.jenkins.io/debian/jenkins.io-2023.key | sudo tee /usr/share/keyrings/jenkins-keyring.asc &gt; /dev/null<br>echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] https://pkg.jenkins.io/debian binary/ | sudo tee /etc/apt/sources.list.d/jenkins.list &gt; /dev/null<br>sudo apt-get update -y<br>sudo apt-get install jenkins -y<br>sudo systemctl enable jenkins</pre><p><strong>vars.json</strong></p><pre>{<br>  &quot;aws_access_key&quot;: &quot;&lt;AWS_ACCESS_KEY&gt;&quot;,<br>  &quot;aws_secret_key&quot;: &quot;&lt;AWS_SECRET_KEY&gt;&quot;,<br>  &quot;ssh_username&quot;: &quot;ubuntu&quot;<br>}</pre><h4>Let’s build the Jenkins Image</h4><p>You should validate the ‘template.json’ file before actually running the build.</p><pre>packer validate -var-file vars.json template.json</pre><p>If everything is okay, you can start building the image</p><pre>packer build -var-file vars.json template.json</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pHrN754gY4oEE3zBNGBVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56pfuGplKTTQmPNm6BxdMA.png" /><figcaption>Jenkins AMI built successfully</figcaption></figure><p>We have successfully created a Jenkins AMI with the ID ami-0261c6446ba1f7d25</p><h4>AWS Console</h4><p>After a successful image build, go to the AWS Console, and you will see that a Jenkins AMI has been created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3ncN8RrcVvgAg3W5mQZrg.png" /></figure><h4>Let’s provision an EC2 instance using the Jenkins AMI we just created</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pewZmOF7YogehYknY0wJLg.png" /></figure><p>Provision this instance on the default VPC and create a new security group with inbound rules allowing traffic on port 8080 from 0.0.0.0/0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5gKw2cOQWBaZ64NYK0aJA.png" /></figure><h4>Jenkins server is up and running</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqJDp64weapXuDz05Oxjmg.png" /></figure><h3>Source Code</h3><p>You can find the complete source code on my Github Repo.</p><p><a href="https://github.com/thearaseng/jenkins-ubuntu-ec2-using-packer">https://github.com/thearaseng/jenkins-ubuntu-ec2-using-packer</a></p><h3>A Cup of Coffee</h3><p>Thank you for reading, and if you find value in what I write, I would greatly appreciate it if you would consider buying me a coffee.</p><p>Or please consider following me on Medium <a href="https://medium.com/@thearaseng">https://medium.com/@thearaseng</a></p><p><em>As someone who blogs, it would mean a lot to me.</em></p><figure><a href="https://www.buymeacoffee.com/thearaseng"><img alt="https://www.buymeacoffee.com/thearaseng" src="https://cdn-images-1.medium.com/max/545/1*jx-d_b9LYbH0ThmH-pxx1Q.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ead12f25a51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Journey to Terraform Associate Certification and Essential Resources for Success]]></title>
            <link>https://medium.com/@thearaseng/my-journey-to-terraform-associate-certification-and-essential-resources-for-success-517bdbe88f2b?source=rss-6c76875b9810------2</link>
            <guid isPermaLink="false">https://medium.com/p/517bdbe88f2b</guid>
            <category><![CDATA[hashicorp-certified]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud-certification]]></category>
            <dc:creator><![CDATA[Theara Seng]]></dc:creator>
            <pubDate>Tue, 01 Aug 2023 17:55:52 GMT</pubDate>
            <atom:updated>2023-08-01T17:55:52.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeg3X1lnI4CRGU_oaFW1DA.png" /></figure><p>As many of you already know, I recently achieved my Terraform Associate certification. For those aspiring to pursue this certification, I’d like to share a collection of valuable resources that helped me in my journey.</p><p>However, it’s important to note that studying for the exam alone won’t make you a Terraform expert. The key is to get hands-on experience by using it in real projects or job scenarios.</p><p>Here are some resources I recommend:</p><ol><li>Practice, Practice, Practice: Dive in and get hands-on experience as your first step.</li><li>Official HashiCorp Learning Platform: Access free tutorials on the official website: <a href="https://developer.hashicorp.com/terraform/tutorials/certification-003">link</a>.</li><li>Free Practice Exams: Try out free practice exams at these links: <a href="https://codingnconcepts.com/post/terraform-associate-exam-questions/">CodingNConcepts</a> | <a href="https://www.examtopics.com/exams/hashicorp/terraform-associate/">ExamTopics</a></li><li>Free Certification Prep on YouTube: Check out freeCodeCamp.org’s YouTube channel for helpful preparation videos: <a href="https://youtu.be/V4waklkBC38">link</a>.</li><li>Paid Sample Practice Exam on Medium: Access paid sample questions on Medium: <a href="https://medium.com/bb-tutorials-and-thoughts/250-practice-questions-for-terraform-associate-certification-7a3ccebe6a1a">link</a>.</li><li>Paid Practice Test from Whizlabs: Consider Whizlabs’ paid practice test: <a href="https://www.whizlabs.com/learn/course/hashicorp-certified-terraform-associate/337">link</a>.</li><li>Registering for the Actual Certification Exam: Watch this YouTube tutorial on how to register for the exam: <a href="https://youtu.be/NOXKviWY6oc">link</a>.</li></ol><p>Best of luck in your Terraform journey! Feel free to reach out if you have any questions or need further assistance. Together, let’s continue learning and growing in this exciting field! 🌟</p><p><a href="https://www.credly.com/badges/6e688d59-dc28-4bc6-acc8-d6c42689ec93/public_url">My Terraform Associate certification</a></p><p>Learn more about me: <a href="http://thearaseng.com/">thearaseng.com</a></p><p><a href="https://www.linkedin.com/feed/hashtag/terraformassociate">#TerraformAssociate</a> <a href="https://www.linkedin.com/feed/hashtag/certificationprep">#CertificationPrep</a> <a href="https://www.linkedin.com/feed/hashtag/terraform">#Terraform</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=517bdbe88f2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create and publish your own AWS VPC Terraform Module on the Terraform Registry]]></title>
            <link>https://medium.com/@thearaseng/create-and-publish-your-own-aws-vpc-terraform-module-on-the-terraform-registry-687480dce74a?source=rss-6c76875b9810------2</link>
            <guid isPermaLink="false">https://medium.com/p/687480dce74a</guid>
            <category><![CDATA[aws-vpc]]></category>
            <category><![CDATA[vpc]]></category>
            <category><![CDATA[terraform-registry]]></category>
            <category><![CDATA[terraform-modules]]></category>
            <category><![CDATA[aws-vpc-terraform]]></category>
            <dc:creator><![CDATA[Theara Seng]]></dc:creator>
            <pubDate>Sun, 04 Dec 2022 08:09:11 GMT</pubDate>
            <atom:updated>2022-12-04T09:16:03.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*O78hv03Nn-5iih4Qpb_MCQ.jpeg" /></figure><p>What is Terraform Module?</p><p>Terraform Modules are small, reusable Terraform configurations that let you manage a group of related resources as if they were a single resource. Modules are helpful for managing your IaC resources and making them reusable across your organization. How do we construct it?</p><p>In this post, we’ll show you how to create your own AWS VPC Terraform Module and share it with the world via the Terraform Registry.</p><h3>Requirements</h3><ul><li>knowledge of Terraform. Know what Terraform and IaC are.</li><li>knowledge of VPC (Virtual Private Cloud).</li><li>Basic knowledge of the AWS cloud is required.</li><li>GitHub account</li></ul><h3>What are we going to build?</h3><p>Following the below diagrams, we will develop a Terraform module to provision AWS VPC resources. The AWS VPC will consist of many resources, including the following:</p><ul><li>VPC itself</li><li>Internet Gateway</li><li>Private subnets</li><li>Public subnets</li><li>one NAT Gateway on each availability zone</li><li>Last but not least, we have routing tables that manage the traffic within our VPC.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*sLKQK6afA4j5EuO4-hscOg.jpeg" /><figcaption>AWS VPC</figcaption></figure><h3>Getting started</h3><p>The first step is to code the <strong>Terraform module</strong> that generates all the required resources.</p><h3>Terraform Versions</h3><p>Let’s define the required Terraform version and AWS provider version.</p><p><strong>versions.tf</strong></p><pre>terraform {<br>  required_version = &quot;~&gt; 1.3.2&quot;<br>  required_providers {<br>    aws = {<br>      version = &quot;~&gt; 4.34.0&quot;<br>    }<br>  }<br>}</pre><h3>Terraform Variables</h3><p>Define variables that we use in the module.</p><ul><li><strong>vpc_cidr_block</strong>: CIDIR range of VPC</li><li><strong>azs</strong>: List of availability zones</li><li><strong>public_subnet_cidrs</strong>: List of CIDIR ranges of public subnets</li><li><strong>private_subnet_cidrs</strong>: List of CIDIR ranges of private subnets</li></ul><p><strong>variables.tf</strong></p><pre>variable &quot;vpc_name&quot; {<br>  type    = string<br>}<br><br>variable &quot;vpc_cidr_block&quot; {<br>  type    = string<br>}<br><br>variable &quot;azs&quot; {<br>  type        = list(string)<br>  description = &quot;Availability Zones&quot;<br>}<br><br>variable &quot;public_subnet_cidrs&quot; {<br>  type        = list(string)<br>  description = &quot;Public Subnet CIDR&quot;<br>}<br><br>variable &quot;private_subnet_cidrs&quot; {<br>  type        = list(string)<br>  description = &quot;Private Subnet CIDR&quot;<br>}</pre><h3>VPC &amp; Internet Gateway</h3><p>All the resources will be defined in a single file, <strong>main.tf</strong>.</p><p>VPC and Internet Gateway are the two most important resources, and we will define them at the beginning of the file.</p><p><strong>main.tf</strong></p><pre>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block = var.vpc_cidr_block<br><br>  tags = {<br>    Name = &quot;${var.vpc_name}-VPC&quot;<br>  }<br>}<br><br>resource &quot;aws_internet_gateway&quot; &quot;gw&quot; {<br>  vpc_id = aws_vpc.main.id<br><br>  tags = {<br>    Name = &quot;${var.vpc_name} IG&quot;<br>  }<br>}</pre><h3>Subnets</h3><p>The number of subnets will be determined by the list of AZs passed from the variable.</p><p>Each AZ will have one private subnet and one public subnet, so we use count to iterate through each AZ.</p><pre>resource &quot;aws_subnet&quot; &quot;public_subnets&quot; {<br>  count             = length(var.azs)<br>  vpc_id            = aws_vpc.main.id<br>  availability_zone = element(var.azs, count.index)<br>  cidr_block        = element(var.public_subnet_cidrs, count.index)<br><br>  tags = {<br>    Name = &quot;Public Subnet ${count.index + 1}&quot;<br>  }<br>}<br><br>resource &quot;aws_subnet&quot; &quot;private_subnets&quot; {<br>  count             = length(var.azs)<br>  vpc_id            = aws_vpc.main.id<br>  availability_zone = element(var.azs, count.index)<br>  cidr_block        = element(var.private_subnet_cidrs, count.index)<br><br>  tags = {<br>    Name = &quot;Private Subnet ${count.index + 1}&quot;<br>  }<br>}</pre><h3>NAT Gateway</h3><p>A NAT gateway serves as a gateway to the outside world, allowing EC2 instances and other resources within private subnets to connect to the Internet.</p><p>One NAT gateway per Availability Zone (AZ) is created to minimize cloud costs.</p><p>Each NAT gateway needs an elastic IP address.</p><p>To generate elastic IP addresses and NAT gateways, we iterate over the total number of AZs using Terraform’s count function.</p><pre>resource &quot;aws_eip&quot; &quot;nat_gateways&quot; {<br>  count = length(aws_subnet.private_subnets)<br>  vpc   = true<br>}<br><br>resource &quot;aws_nat_gateway&quot; &quot;nat_gw&quot; {<br>  count         = length(aws_subnet.private_subnets)<br>  allocation_id = element(aws_eip.nat_gateways, count.index).id<br>  subnet_id     = element(aws_subnet.private_subnets, count.index).id<br>}</pre><h3>Route tables</h3><p>A route table has a set of rules, called routes, that tell your subnet where to send network traffic.</p><p>We’re going to make two different kinds of route tables. One kind of route table is for public subnets, and the other kind is for private subnets.</p><ul><li>Public subnet route table: All packets going to cidr block (“0.0.0.0/0”) would be sent to the Internet gateway.</li><li>Public subnet rout table: All traffic going to cidr block (“0.0.0.0/0”) would be sent to the NAT gateway in that AZ.</li></ul><p>Public subnet’s <strong>route table</strong> and its route_table_association</p><pre>resource &quot;aws_route_table&quot; &quot;public_subnets&quot; {<br>  vpc_id = aws_vpc.main.id<br><br>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.gw.id<br>  }<br><br>  tags = {<br>    Name = &quot;Public Subnet Route Table&quot;<br>  }<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;public_subnet_asso&quot; {<br>  count          = length(aws_subnet.public_subnets)<br>  subnet_id      = element(aws_subnet.public_subnets[*].id, count.index)<br>  route_table_id = aws_route_table.public_subnets.id<br>}</pre><p>Private subnet’s <strong>route table</strong> and its route_table_association</p><pre>resource &quot;aws_route_table&quot; &quot;private_subnets&quot; {<br>  count  = length(aws_nat_gateway.nat_gw)<br>  vpc_id = aws_vpc.main.id<br><br>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = element(aws_nat_gateway.nat_gw, count.index).id<br>  }<br><br>  tags = {<br>    Name = &quot;Private Subnet Route Table&quot;<br>  }<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;private_subnet_asso&quot; {<br>  count          = length(aws_subnet.private_subnets)<br>  subnet_id      = element(aws_subnet.private_subnets[*].id, count.index)<br>  route_table_id = element(aws_route_table.private_subnets[*].id, count.index)<br>}</pre><h3>Push code Github</h3><p>We’ve finished writing the Terraform module.</p><p>Let’s commit and push the code to a public Github repo so Terraform Registry can read it and add it to its public registry.</p><p>The prerequisites for a repository to qualify as a source for the Terraform Registry:</p><ul><li>The repository must be public.</li><li>The repository name must be written according to Terraform module convention: <strong>terraform-&lt;&lt; provider-name &gt;&gt;-&lt;&lt; module-name &gt;&gt;</strong></li></ul><p>For instance, our repository name would be <strong>terraform-aws-vpc</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrSVttlMmNhtyS1Zi2mgcg.png" /><figcaption>GitHub Repo</figcaption></figure><h3>Coffee time</h3><p>Having trouble keeping up?</p><p>Take a moment to refresh with a cup of coffee before we move on.</p><h3>Publish Terraform module to public registry</h3><h3>Module Version</h3><p>Modules cannot be created without a version.</p><p>Let’s create the first version of the module by creating a Git tag.</p><pre>git tag v1.0.0<br>git push origin v1.0.0</pre><h3>Create Terraform Module</h3><p>Coding is tedious; now comes the exciting part.</p><p>Using the intuitive Terraform registry dashboard, one can easily publish a module to a registry.</p><ul><li>Go to <a href="https://registry.terraform.io/">https://registry.terraform.io</a></li><li>Go to <strong>Publish</strong></li><li>Click on <strong>Module</strong> in the drop down</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lm3n53ZGqoUzmqvsXd7z6A.png" /></figure><ul><li>Then you’ll be asked to Sign In with <strong>Github</strong> Acccount.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kMCSUfVabdi_aPPbTV7NQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hScMXze2PzSyGPUx9vuneA.png" /></figure><ul><li>Input the two-factor authentication code if your account has enabled it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_l1tL4hwvblSKsSHIl2abg.png" /></figure><p>You will be redirected to the Terraform Registry homepage once you have successfully authenticated.</p><p>Agian.</p><ul><li>Go to <strong>Publish</strong></li><li>Click on <strong>Module</strong> in the drop down</li><li>Select a Github repository that has recently been pushed to <strong>Github</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7Tbb3F9PaI6b3VI3ctVFQ.png" /></figure><ul><li>Tick on <strong>Agree to the Term of Use</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8YCHnHdyq6sDccaxGsT-w.png" /></figure><ul><li>Click on <strong>PUBLISH MODULE</strong> button</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*B0hfxLkGXuve_UXLORbpMA.png" /></figure><p>Voila! You just published your first Terraform module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WzU7WrBfafPKNEVTW8B73w.png" /><figcaption>Terraform Registry</figcaption></figure><h3>Example</h3><p>Unless you actually use the Terraform module to provision resources, it’s not very helpful.</p><p>So, let’s make a Terraform project that makes use of the newly released Terraform Module.</p><p>Our Terraform project would come with ordinary files such as:</p><ul><li><strong>provider.tf</strong></li><li><strong>version.tf</strong></li><li><strong>main.tf</strong></li></ul><p><strong>provider.tf</strong></p><pre>provider &quot;aws&quot; {<br>  region  = &quot;ap-southeast-1&quot;<br>}</pre><p><strong>version.tf</strong></p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      version = &quot;~&gt; 4.34.0&quot;<br>    }<br>  }<br><br>  required_version = &quot;~&gt; 1.3.2&quot;<br>}</pre><p>The main.tf file will use the Terraform module and set the required variables.</p><p><strong>main.tf</strong></p><pre>module &quot;vpc&quot; {<br>  source               = &quot;thearaseng/vpc/aws&quot;<br>  version              = &quot;1.0.2&quot;<br>  vpc_name             = &quot;example&quot;<br>  vpc_cidr_block       = &quot;10.0.0.0/16&quot;<br>  azs                  = [&quot;ap-southeast-1a&quot;, &quot;ap-southeast-1b&quot;]<br>  public_subnet_cidrs  = [&quot;10.0.1.0/24&quot;, &quot;10.0.2.0/24&quot;]<br>  private_subnet_cidrs = [&quot;10.0.3.0/24&quot;, &quot;10.0.4.0/24&quot;]<br>}</pre><h3>Terraform Apply</h3><p>Let’s apply the Terraform plan and see what we’ve done so far.</p><pre>terraform init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*_Leymes0uNrN_eMhIwhm0g.png" /></figure><pre>terraform plan</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pRbPLPDo4dtcIxf2EN-WQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTn1GhLwCqVNZKPFxWC5AA.png" /></figure><pre>terraform apply -auto-approve</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FHsjHt3NdHA6QVTTrg1YA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*I86PUkgZGNY-A-T0ILScjw.png" /></figure><h3>Result</h3><p>Congratulations. You made it. :)</p><p>All AWS resources have been provisioned successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*_O9noHd8kD9BViwZIx4_eg.png" /></figure><h3>Destroy</h3><p>Don’t be taken aback by the AWS monthly bill.</p><p>You should destroy Terraform resources after you’ve done testing it.</p><p>Let’s DESTROY it.</p><pre>terraform destroy -auto-approve</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CE-adLi_q1oNNIL4lcwsPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*9oYDjRh6g4Jq8QOgSf9IAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*MrvPanHx1u1svWoY15CASw.jpeg" /></figure><h3>Source Code</h3><p>You can find the complete source code on the public Gitlab Repo.</p><p>Terraform Module: <a href="https://github.com/thearaseng/terraform-aws-vpc/tree/main">https://github.com/thearaseng/terraform-aws-vpc/tree/main</a></p><p>Terraform Example: <a href="https://github.com/thearaseng/terraform-aws-vpc/tree/example">https://github.com/thearaseng/terraform-aws-vpc/tree/example</a></p><h3>A Cup of Coffee</h3><p>Thank you for reading, and if you find value in what I write, I would greatly appreciate it if you would consider buying me a coffee.</p><p>Or please consider following me on Medium <a href="https://medium.com/@thearaseng">https://medium.com/@thearaseng</a></p><p><em>As someone who blogs, it would mean a lot to me.</em></p><figure><a href="https://www.buymeacoffee.com/thearaseng"><img alt="https://www.buymeacoffee.com/thearaseng" src="https://cdn-images-1.medium.com/max/545/1*jx-d_b9LYbH0ThmH-pxx1Q.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=687480dce74a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build S3 Static Website and CloudFront Using Terraform and Gitlab]]></title>
            <link>https://medium.com/@thearaseng/build-s3-static-website-and-cloudfront-using-terraform-and-gitlab-888a8ec1d37d?source=rss-6c76875b9810------2</link>
            <guid isPermaLink="false">https://medium.com/p/888a8ec1d37d</guid>
            <category><![CDATA[s3-static-site]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <dc:creator><![CDATA[Theara Seng]]></dc:creator>
            <pubDate>Sun, 27 Nov 2022 06:52:55 GMT</pubDate>
            <atom:updated>2023-09-10T18:24:08.850Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’m guiding you through how we could set up an S3 static website and CloudFront using Terraform and Gitlab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*fPWi9YSTmj8wDLvJShqNdQ.png" /></figure><p>We focus on how to implement IaC (Terraform) and use Gitlab CI as our Continuous Integration tool.</p><h3>What is Infrastructure as Code (IaC)</h3><p>Infrastructure as Code (IaC) manages and provides an infrastructure through code instead of through manual processes.</p><p>With IaC, configuration files containing your infrastructure specifications are created, making it easier to edit and distribute configurations. Terraform is one of the Infrastructure as Code (IaC) tools developed by HashiCorp.</p><p>Terraform is one way to build and manage the infrastructure in the cloud platform such as Azure, AWS, GCP, etc.</p><p>If it’s your first time hearing about IaC or Infrastructure as Code, we can refer to this <a href="https://www.terraform.io/intro">link</a> to get you comfortable.</p><h3>Terraform file structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*-0Ndz7YqQndzTjkRRmnChA.png" /></figure><p>All the Terraform files locate within the terraform folder.</p><p>Please start with the first file, <strong>backend.tf</strong>, which defines where Terraform stores its state data files.</p><p>In our case, we will use Gitlab as our Terraform state storage.</p><p>The contents of the <strong>backend.tf</strong></p><pre>terraform {<br>  backend &quot;http&quot; {<br>  }<br>}</pre><p><strong>variables.tf</strong> and <strong>version.tf</strong> are where input variables and Terraform provider constraint are defined.</p><p>The contents of the <strong>variables.tf</strong></p><pre>variable &quot;region&quot; {<br>  type = string<br>  default = &quot;ap-southeast-1&quot;<br>}<br><br>variable &quot;s3_name&quot; {<br>  type = string<br>}</pre><p>The contents of the <strong>version.tf</strong></p><pre>terraform {<br>  required_providers {<br>    aws = {<br>      version = &quot;~&gt; 4.34.0&quot;<br>    }<br>  }<br>}</pre><p><strong>Note:</strong> The region is set to ap-southeast-1 (Singapore) as it’s my closest region which varies from your location. You can find a list of AWS regions here. : <a href="https://howto.lintel.in/list-of-aws-regions-and-availability-zones">https://howto.lintel.in/list-of-aws-regions-and-availability-zones</a></p><p><strong>s3.tf</strong> is where S3 and its ACL and bucket policy are defined.</p><p>The contents of the <strong>s3.tf</strong></p><pre>resource &quot;aws_s3_bucket&quot; &quot;this&quot; {<br>  bucket = var.s3_name<br>}<br><br>resource &quot;aws_s3_bucket_acl&quot; &quot;this&quot; {<br>  bucket = aws_s3_bucket.this.id<br>  acl    = &quot;private&quot;<br>}<br><br>resource &quot;aws_s3_bucket_website_configuration&quot; &quot;this&quot; {<br>  bucket = aws_s3_bucket.this.bucket<br><br>  index_document {<br>    suffix = &quot;index.html&quot;<br>  }<br><br>  error_document {<br>    key = &quot;index.html&quot;<br>  }<br><br>}<br><br>resource &quot;aws_s3_bucket_policy&quot; &quot;this&quot; {<br>  bucket = aws_s3_bucket.this.id<br><br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Id      = &quot;AllowGetObjects&quot;<br>    Statement = [<br>      {<br>        Sid       = &quot;AllowPublic&quot;<br>        Effect    = &quot;Allow&quot;<br>        Principal = &quot;*&quot;<br>        Action    = &quot;s3:GetObject&quot;<br>        Resource  = &quot;${aws_s3_bucket.this.arn}/**&quot;<br>      }<br>    ]<br>  })<br>}</pre><p><strong>cloudfront.tf</strong> is where AWS CloudFront and its default caching behaviour are defined. The important thing is that it uses S3, defined earlier as its default origin.</p><p>The contents of the <strong>cloudfront.tf</strong></p><pre>locals {<br>  s3_origin_id   = &quot;${var.s3_name}-origin&quot;<br>  s3_domain_name = &quot;${var.s3_name}.s3-website-${var.region}.amazonaws.com&quot;<br>}<br><br>resource &quot;aws_cloudfront_distribution&quot; &quot;this&quot; {<br>  <br>  enabled = true<br>  <br>  origin {<br>    origin_id                = local.s3_origin_id<br>    domain_name              = local.s3_domain_name<br>    custom_origin_config {<br>      http_port              = 80<br>      https_port             = 443<br>      origin_protocol_policy = &quot;http-only&quot;<br>      origin_ssl_protocols   = [&quot;TLSv1&quot;]<br>    }<br>  }<br><br>  default_cache_behavior {<br>    <br>    target_origin_id = local.s3_origin_id<br>    allowed_methods  = [&quot;GET&quot;, &quot;HEAD&quot;]<br>    cached_methods   = [&quot;GET&quot;, &quot;HEAD&quot;]<br><br>    forwarded_values {<br>      query_string = true<br><br>      cookies {<br>        forward = &quot;all&quot;<br>      }<br>    }<br><br>    viewer_protocol_policy = &quot;redirect-to-https&quot;<br>    min_ttl                = 0<br>    default_ttl            = 0<br>    max_ttl                = 0<br>  }<br><br>  restrictions {<br>    geo_restriction {<br>      restriction_type = &quot;none&quot;<br>    }<br>  }<br>  <br>  viewer_certificate {<br>    cloudfront_default_certificate = true<br>  }<br><br>  price_class = &quot;PriceClass_200&quot;<br>  <br>}</pre><h3>Gitlab CI/CD</h3><p>Now we got Terraform files in place. Next, to provision the resources, Terraform will need CI/CD tools to do this particular job.</p><p>Gitlab CI is a robust CI/CD system with many built-in templates that we use to integrate with Terraform. The important life cycle of IaC (Infrastructure as Code) are:</p><ul><li>Initialize (Validate)</li><li>Plan (Build)</li><li>Apply (Deploy)</li><li>Destroy</li></ul><p>Gitlab has come with built-in templates for such IaC life cycle events. And the best fit template is Terraform/Base.gitlab-ci.yml that we’re going to use.</p><p>A regular Gitlab YAML file would come with the list of <strong>templates</strong>, <strong>stages</strong>, and some user-defined <strong>variables</strong></p><pre>include:<br>  - template: Terraform/Base.gitlab-ci.yml<br><br>stages:<br>  - validate<br>  - build<br>  - deploy<br>  - cleanup<br><br>variables:<br>  TF_STATE_NAME: dev-tf-state<br>  TF_CACHE_KEY: dev-tf-cache<br>  TF_ROOT: terraform # the terraform files are in this subdirectory. set TF_ROOT accordingly if yours are different</pre><p>The rest of the Gitlab jobs are:</p><p><strong>validate job</strong></p><pre>validate: # validate stage<br>  extends: .terraform:validate</pre><p><strong>build job</strong></p><pre>build:<br>  extends: .terraform:build<br>  script:<br>    - cd &quot;${TF_ROOT}&quot;<br>    - gitlab-terraform plan<br>      -var &quot;s3_name=${S3_NAME}&quot;<br>    - gitlab-terraform plan-json</pre><p><strong>deploy job</strong></p><pre>deploy:<br>  extends: .terraform:deploy<br>  environment:<br>    name: $TF_STATE_NAME<br>    on_stop: destroy<br>  dependencies:<br>    - build<br>  rules:<br>    - when: always</pre><p><strong>cleanup job</strong></p><pre>destroy:<br>  extends: .terraform:destroy<br>  environment:<br>    name: $TF_STATE_NAME<br>    action: stop<br>  script:<br>    - cd &quot;${TF_ROOT}&quot;<br>    - gitlab-terraform destroy<br>      -var &quot;s3_name=${S3_NAME}&quot;</pre><h3>Gitlab CI/CD variables</h3><p>For CI to authenticate and authorize the provisioning of cloud resources, we need AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.</p><p>Detail on how to get your AWS access key ID and secret access key <a href="https://docs.aws.amazon.com/powershell/latest/userguide/pstools-appendix-sign-up.html">https://docs.aws.amazon.com/powershell/latest/userguide/pstools-appendix-sign-up.html</a></p><p>Hence CI variables needed for this particular Terraform are: <strong>AWS_ACCESS_KEY_ID</strong>, <strong>AWS_SECRET_ACCESS_KEY</strong>, and <strong>S3_NAME</strong> (since Amazon bucket names must be unique across all AWS accounts in all the AWS Regions within a partition)</p><ul><li>AWS_ACCESS_KEY_ID</li><li>AWS_SECRET_ACCESS_KEY</li><li>S3_NAME</li></ul><p>Input all required variables in Gitlab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcxLJqXWYUddj0hYyiChWQ.png" /></figure><h3>Gitlab Pipeline UI</h3><p>The most exciting part is to see what is accomplished in the Gitlab Pipeline portal itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ii7UJe9RZslXTsWYipY9Ow.png" /></figure><p>If everything works properly, we see the stages of the pipeline run successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1sKxaO1-uoVQaUwnmp9Xwg.png" /></figure><h3>AWS Console</h3><h3>Amazon S3</h3><p>The Amazon S3 Console will have a newly provisioned bucket listed here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jLPcIswJTWxquNvHRn4leQ.png" /></figure><h3>Create a hello-world index page</h3><p>Let’s create a simple index.html page that will show a greeting message.</p><p><strong>index.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Hello World&lt;/title&gt;<br>    &lt;style&gt;<br>      h1 {<br>        text-align: center;<br>      }<br>      p {<br>        text-align: center;<br>      }<br>    &lt;/style&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Hello, greeting from the Cloud...&lt;/h1&gt;<br>    &lt;p&gt;This is your very first static page&lt;/p&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Create the index.html with the above HTML code, then upload it to the Amazon S3 bucket just created. Go into the bucket and drag the <strong>index.html</strong> file into the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*RxkbdGDU9vK3a7vnOvvJVA.png" /></figure><p>Then click the <strong>Upload</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SO7UQuZDiGE_rM-WMLtV_A.png" /></figure><h3>Amazon CloudFront</h3><p>The Amazon S3 Console will have an AWS CloudFront just created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROYuK-O8dan0Iu3o-ZEFVg.jpeg" /></figure><h3>S3 Static Website</h3><p>Congratulations. You made it. :) By visiting CloudFront URL, we can view our static website made by the sample index.html.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FAk7IGECkCrJDjLSJFq6A.png" /></figure><p>You can find the complete source code on the public Gitlab Repo.</p><p>Peace!</p><p><a href="https://gitlab.com/thearaseng/s3-static-website-and-cloudfront-using-terraform/-/tree/master">Files · master · Theara Seng / S3 Static Website And CloudFront Using Terraform · GitLab</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888a8ec1d37d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using GitHub Actions, build and push Docker images]]></title>
            <link>https://medium.com/@thearaseng/using-github-actions-build-and-push-docker-images-30d05e58be4b?source=rss-6c76875b9810------2</link>
            <guid isPermaLink="false">https://medium.com/p/30d05e58be4b</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Theara Seng]]></dc:creator>
            <pubDate>Sun, 27 Nov 2022 06:19:04 GMT</pubDate>
            <atom:updated>2022-11-27T06:26:36.369Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuous Integration and Continuous Delivery (CI/CD): GitHub Actions is a platform that lets you automate your build, test, and deployment pipelines. You can set up workflows that build and test every pull request in your repository, or you can deploy merged pull requests to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*5JIcTnXIZpZ6uIsCcuP1nw.jpeg" /></figure><h3>Requirements</h3><ul><li>A gradle Spring Boot project to be dockerized</li><li>GitHub repository</li><li>Docker Hub account</li></ul><h3>What are we going to build?</h3><p>We will set up a GitHub workflow to build Docker images that will run automatically whenever commits are pushed to the repository.</p><h3>Getting started</h3><p>For this job, there are many tips and tricks that can be used. This method is a very easy and straightforward way to get there.</p><h3>The Docker Hub</h3><p>We need to create a repository on Docker Hub. That’s where the container images we create will be pushed.</p><h3>Dockerfile</h3><p>Let’s get started by creating a Dockerfile.</p><p>Because this is a Spring Boot project, we’ll use the openjdk Docker image and a jar file compiled from the Gradle.</p><p>Dockerfile</p><pre>FROM openjdk:8-jdk<br><br>RUN mkdir /app<br><br>COPY app.jar /app/app.jar<br><br>WORKDIR /app<br><br>EXPOSE 8080<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><h3>Github Actions</h3><p>Fun part. The most exciting part is to see what Github Actions can do to help us automatically build Gradle and Docker images without human intervention. Let’s create a main.yml file in .github/workflows folder.</p><p>The workflows would consist of two separate jobs</p><ul><li>build: to build jar file</li><li>build-image: to build Docker image and push to it Docker hub</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*fvgITA1DhO67Z4b63-cwgg.png" /></figure><h3>Build Jar file</h3><p>The very first job of the pipeline is to build a jar file for the Spring Boot application. The simplest way to get started is to look for a sample Github workflow on Github.</p><ul><li>Go to Github Repo</li><li>Actions</li></ul><p>You will see workflows that could be used with your repository. In this case, it seems like the best way to build Spring Boot’s jar file is to use <strong>Java with Gradle</strong> workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFDTcP_DD_bYqn-rH3kNfw.png" /></figure><ul><li>Click on <strong>Configure</strong> button</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFUdfLkgsPUg9ICNmY_FyQ.png" /></figure><p><strong>main.yaml</strong></p><p>Let’s use the above sample workflows to make <strong>main.yml</strong> file.</p><p>The should look like This is how <strong>main.yml</strong> should look:</p><pre>name: Docker CI with Gradle<br><br>on:<br>  push:<br>    branches: [ &quot;main&quot; ]<br><br>permissions:<br>  contents: read<br><br>jobs:<br>  build:<br><br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - uses: actions/checkout@v3<br>      - uses: actions/setup-java@v3<br>        with:<br>          distribution: temurin<br>          java-version: 11<br>          <br>      - name: Setup Gradle<br>        uses: gradle/gradle-build-action@v2<br>      <br>      - name: Execute Gradle build<br>        run: |<br>          chmod +x ./gradlew<br>          ./gradlew bootJar          <br><br>      - name: Execute Gradle build<br>        run: |<br>          chmod +x ./gradlew<br>          ./gradlew bootJar          <br><br>      - name: Copy Jar file<br>        run: mv build/libs/$(ls build/libs) app.jar<br><br>      - uses: actions/upload-artifact@master<br>        with:<br>          name: jar-file<br>          path: app.jar</pre><ul><li>I’ve replaced the gradle build with ./gradlew bootJar as this Spring Boot App comes with its own gradle wrapper.</li><li>I also moved the compiled app.jar from the build directory to the current directory because the Dockerfile expects it to be in that location.</li><li>To be able to share the jar file with the next job (<strong>build-image</strong> that we’re going to do later) by using upload-artifact actions.</li></ul><p>Let’s add the main.yml file and push it to Github repo. If everything was set up right, the workflow would be running on the Github actions page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QL7Cxo_xJInVx5fKqxKOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FemOIRT4fe3E1ey72oLjDQ.png" /></figure><h3>Build Docker Image</h3><p>Just like we did for the last job, we can find a lot of public examples of workflows.</p><pre>build-image:<br><br>    runs-on: ubuntu-latest<br>    needs: build<br><br>    steps:<br>      <br>      - uses: actions/checkout@v3<br><br>      - uses: actions/download-artifact@master<br>        with:<br>          name: jar-file<br>          path: app.jar<br><br>      - name: Set up QEMU<br>        uses: docker/setup-qemu-action@v2<br>      <br>      - name: Set up Docker Buildx<br>        uses: docker/setup-buildx-action@v2<br>      <br>      - name: Login to Docker Hub<br>        uses: docker/login-action@v2<br>        with:<br>          username: ${{ secrets.DOCKERHUB_USERNAME }}<br>          password: ${{ secrets.DOCKERHUB_TOKEN }}<br><br>      - name: Set env<br>        run: echo &quot;DATE=$(date +%s)&quot; &gt;&gt; $GITHUB_ENV<br>      <br>      - name: Build and push<br>        uses: docker/build-push-action@v3<br>        with:<br>          context: .<br>          push: true<br>          tags: thearaseng/dockerized-spring-boot-app:${{ env.DATE }}</pre><p>noted that we need to create two important variables: <strong>DOCKERHUB_USERNAME</strong> and <strong>DOCKERHUB_TOKEN</strong></p><h4>Generate Docker Hub Access Token</h4><p>Because we’re going to push the images to Docker Hub, we need an access token with read and write permission. To generate this access token.</p><ul><li>Go to Docker Hub setting page: <a href="https://hub.docker.com/settings/security">https://hub.docker.com/settings/security</a></li><li>Click on <strong>New Access Token</strong> button</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cF1Ou563yZ6i3HgQ0T5Eg.png" /></figure><ul><li>Fill out the Access Token Description field</li><li>In <strong>Access permission</strong> dropdown, choose <strong>Read &amp; Write</strong></li><li>Click on <strong>Generate</strong> button</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PC8FnarrIFSnyqviVNoFAg.png" /></figure><ul><li>Make a copy of the access token and don’t give it to anyone else.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLZ2KdEtfjJ94i1m_tOb1Q.png" /></figure><h4>Github Actions secrets</h4><p>Since they are very sensitive variables, we are going to store them in Github Actions secrets.</p><ul><li>Go to <strong>Settings</strong> &gt; Secrets &gt; Actions</li><li>Click on <strong>New repository secret</strong> button</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gG5zEfVVDK9nZ1_mqYUpeQ.png" /></figure><ul><li>Fill out the Docker Hub account name</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8_gFsE2z3iMcWW8AMOKkg.png" /></figure><ul><li>Fill out the Docker Hub access token</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpWUt6Flbzk-SujLLwddDA.png" /></figure><h3>Final Result</h3><p>Let’s commit the final <strong>main.yml</strong> file and go to the Github Actions page</p><h3>Github Actions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mpENb1_hDTi4PIh9BJM5Q.png" /></figure><h3>Docker Repo</h3><p>We can see Docker tags that have been pushed from Github Actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tAP0_xGDgBTWLfdAdDH20A.png" /></figure><p>Congratulations. You made it. :)</p><p>You can find the complete source code on the public Gitlab Repo.</p><p><a href="https://github.com/thearaseng/dockerized-spring-boot-app/tree/main">https://github.com/thearaseng/dockerized-spring-boot-app/tree/main</a></p><p>Peace!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*IrK6PBMxVy6IKyxrUBLcYg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30d05e58be4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>