<?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 Rajiya Shaik on Medium]]></title>
        <description><![CDATA[Stories by Rajiya Shaik on Medium]]></description>
        <link>https://medium.com/@Rajiya.Shaik?source=rss-10e98ddb953e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KiK-qxOTwL0ESuNS</url>
            <title>Stories by Rajiya Shaik on Medium</title>
            <link>https://medium.com/@Rajiya.Shaik?source=rss-10e98ddb953e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:11:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Rajiya.Shaik/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[Break a Monolithic Application into Microservices with AWS Copilot, Amazon ECS, Docker, and AWS…]]></title>
            <link>https://medium.com/@Rajiya.Shaik/break-a-monolithic-application-into-microservices-with-aws-copilot-amazon-ecs-docker-and-aws-0b3ce4c932e4?source=rss-10e98ddb953e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b3ce4c932e4</guid>
            <dc:creator><![CDATA[Rajiya Shaik]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 20:58:17 GMT</pubDate>
            <atom:updated>2025-01-28T20:58:17.193Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Break a Monolithic Application into Microservices with AWS Copilot, Amazon ECS, Docker, and AWS Fargate</strong></h3><p><strong>I. Introduction</strong></p><p>In this Project, you will deploy a monolithic node.js application to a Docker container, then decouple the application into microservices without any downtime. The node.js application hosts a simple message board with threads and messages between users.</p><p>In the dynamic landscape of modern software development, the transition from monolithic applications to microservices architecture has become a strategic imperative for organizations aiming to enhance scalability, agility, and overall system maintainability. Monolithic applications, characterized by their tightly interconnected components, often face challenges as they scale, hindering the ability to deploy updates independently. Microservices, on the other hand, advocate for a modular approach, breaking down the application into smaller, independent services, each responsible for specific business functionalities. This paradigm shift allows for more flexible development and deployment, fostering a culture of continuous integration and delivery.</p><p>To facilitate this transformative journey, a powerful combination of tools emerges as a key enabler. AWS Copilot, a user-friendly command-line interface, streamlines the entire lifecycle of containerized applications, making it easier for developers to focus on building features rather than managing infrastructure. Amazon ECS (Elastic Container Service) provides a scalable and fully managed container orchestration service, offering developers the flexibility to deploy and manage containers effortlessly. Docker, a widely adopted containerization platform, ensures consistency in deployment across diverse environments, promoting seamless collaboration and integration.</p><p>As the foundation of this microservices architecture, AWS Fargate enters the scene to abstract away the complexities of infrastructure management. By providing on-demand, serverless compute for containers, Fargate empowers developers to focus solely on their applications without the burden of server provisioning or maintenance. The integration of AWS Copilot, Amazon ECS, Docker, and AWS Fargate forms a potent alliance, offering organizations the tools needed to successfully break down monolithic barriers, embark on a microservices journey, and unlock the full potential of cloud-native development on the AWS platform. This cohesive ecosystem facilitates a smoother transition and positions businesses to thrive in the ever-evolving landscape of digital innovation.</p><p><strong>Architecture Diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*PC19tqsTB5GwrsUBEas6yA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*QiftBODIGGEl1_P5omL0XA.png" /></figure><p><strong>II.Prerequisites: </strong>An AWS account</p><p><strong>III.Billing:</strong></p><p>In this Project, we are using the ECS — Elastic Container Services, which is not a free service. You need to pay <strong>$0.01025 per hour</strong></p><p>You pay <strong>$0.01025 per hour</strong> for each managed ECS Anywhere on-premises instance. An on-premises instance is a customer-managed instance that has been registered with an Amazon ECS cluster and runs the Amazon ECS container agent.</p><p>We have used it for 7.665 hours and charged around 0.38 USD but if you consume more time with this lab, you will likely get more charge for this lab.</p><p><strong>IV. Steps:</strong></p><p><strong>This Project is divided into the following Steps.</strong></p><p><strong>1.</strong> <strong>CREATING AN EC2 INSTANCE &amp; INSTALLING AWS CLI, DOCKER &amp; COPILOT:</strong></p><p>Setting up an AWS account and configuring the AWS CLI is essential for accessing and managing cloud resources. Installing Docker allows for efficient containerization of applications, ensuring consistency across environments. AWS Copilot simplifies the deployment and operation of these containerized apps, streamlining tasks like scaling and monitoring. In short, it’s all about empowering efficient cloud management and application deployment. We can do this on our physical laptop or desktop as well but for more exposure purposes we are using a virtual machine.</p><p><strong>1.1 Create Ubuntu Instance:</strong></p><p>Ø Log in to your AWS console.</p><p>Ø Search for <strong>EC2</strong> in the search bar and click on it.</p><p>Ø Once you are at the EC2 Dashboard, click on <strong>Launch</strong> to launch an instance.</p><p>Ø In the Name and Tags step you can add tags to an instance, here tags help you to categorize AWS resources in different ways, for example, by owner, environment, or purpose.Here name is specified as <strong>Ubuntu-server</strong></p><p>Ø Choose <strong>Ubuntu</strong>, select <strong>Ubuntu Server (HVM)</strong> architecture, and Click on<strong> Select</strong>.</p><p>Ø For Select the <strong>t2.micro</strong> instance type, if you want you may select another instance type but they are chargeable so we choose the t2.micro instance type which is eligible for the free tier and limited resources.</p><p>Ø Select an existing key pair or create a new one, we will Create a new one, enter the name of the Key-pair as <strong>ubuntu-Key</strong>, select <strong>.ppk,</strong> and Create the Key Pair.</p><p>Ø Now select HTTP and HTTPS Ports under Network Setting.</p><p>Ø Now review all the things you have configured and Click on<strong> Launch Instance</strong>.</p><p>Ø Now Click on <strong>Instances</strong>.</p><p>Ø Refresh and you shall see your instance is Up and Running, and the <strong>Status check</strong> has changed to <strong>2/2 checks.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*-aJftgvTuHXrJBbW7XydJw.png" /><figcaption><strong>Ubuntu Instance</strong></figcaption></figure><p><strong>Now, we have successfully created our Ubuntu Instance using EC2.</strong></p><p><strong>Connect to Ubuntu Instance:</strong></p><p>o Select your Instance and Click on <strong>Connect</strong>.</p><p>Ø Select EC2 Instance Connect and Click on the <strong>Connect.</strong><br> Now you shall be redirected to a new window and you shall see the Ubuntu CLI.</p><p><strong>1.2 Install AWS CLI on Ubuntu</strong></p><p>Ø Install unzip on Ubuntu.</p><p>o sudo apt install unzip</p><p>Ø Download the AWS CLI using the Curl Command.</p><pre>curl &quot;https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip&quot; -o &quot;awscliv2.zip&quot;</pre><p>Ø Unzip the AWS CLI package.</p><pre>unzip awscliv2.zip</pre><p>Ø Run the Install Program. The installation command uses a file named install in the newly unzipped aws directory.</p><pre>sudo ./aws/install</pre><p>Ø Confirm the installation with the following command.</p><pre>aws --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*OnbLtVwl_6ViSMz-e6gXIw.png" /></figure><p><strong>Creating IAM User &amp; AWS Access Keys:</strong></p><p>In this step, we will be setting up an IAM user and managing their Access Keys and Secret Access Keys. <strong>We’re avoiding the root user to keep things simple and prevent issues with role assumption as we move through the Next Steps.</strong></p><p>Ø Log in to your AWS console and go to the IAM service section.</p><p>Ø Under <strong>IAM Dashboard</strong> and then click on <strong>Users </strong>from left-hand side navigation panel.</p><p>Ø Now Click on <strong>Add user</strong>.</p><p>Ø Provide the <strong>username</strong>, select Enable Console Access then select Custom Password and click on <strong>Next.</strong></p><p>Ø Click on Attach Policy Directly and Select the <strong>Administrator access</strong> then click on <strong>Next.</strong></p><p>Ø Review the settings and click on <strong>Create User.</strong></p><p>Ø Download the .csv file and click on Return to the user list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*1jkxXAFSQiKOu1hghQQE9w.png" /></figure><p><strong>Create Access Keys for IAM User:</strong></p><p>Ø Now go to the IAM user dashboard, click on the user we have just created in the previous steps, and then go to the <strong>Security Credentials.</strong></p><p>Ø Scroll down and Under the Access Keys click on <strong>Create Access Key.</strong></p><p>Ø Click on the <strong>Command line interface,</strong> select the <strong>checkbox</strong> and click on <strong>Next.</strong></p><p>Ø Provide a Tag as a key and click on <strong>Create access key.</strong></p><p>Ø <strong>Download the .csv</strong> file and click on <strong>Done.</strong></p><p>Ø Now download the CSV file. This file contains user details like Access key ID &amp; Secret key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*8_N97jPkUnh_CvFQJhaEAw.png" /></figure><p><strong>1.3 Configure AWS CLI:</strong></p><p>Now we are going to Configure AWS CLI to access AWS services. This explains how to configure the settings that the AWS Command Line Interface (AWS CLI) uses to interact with AWS. These include your security credentials, the default output format, and the default AWS Region.</p><p>Now connect to the Ubuntu Instance again.</p><p>To configure the installation, run the following command.</p><pre>aws configure</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*XgoNvczf6tK5hgIzO1TclA.png" /></figure><p><strong>Thus, we have successfully Configured AWS CLI on Ubuntu Instance.</strong></p><p><strong>1.4 Install Docker Engine on Ubuntu:</strong></p><p>Ø Connect to the Ubuntu instance and update the apt package.</p><pre>sudo apt-get update</pre><p>Ø Install packages to allow apt to use a repository over HTTPS:</p><pre>sudo apt-get install \<br>ca-certificates \<br>curl \<br>gnupg \<br>lsb-release</pre><p>This command uses the <strong><em>apt-get</em></strong> package manager to install the specified packages on a Debian-based system.</p><p>Ø Add Docker’s official GPG key:</p><pre>sudo mkdir -m 0755 -p /etc/apt/keyrings</pre><p>This command creates a directory named “keyrings” in the “/etc/apt/” directory on a Unix-like system</p><pre>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg - dearmor -o /etc/apt/keyrings/docker.gpg</pre><p>Ø This command uses <strong><em>curl</em></strong> to download the Docker GPG (GNU Privacy Guard) public key from the specified URL. It then pipes (|) the output to <strong><em>gpg</em></strong> with the <strong>— dearmor</strong> option, which converts the GPG key from its binary format to plain text.</p><p>Ø Use the following command to set up the stable repository. <br> (Note: The below is a single command, please Copy and paste the command on a notepad first then execute it.)</p><pre>echo \<br>&quot;deb [arch=$(dpkg - print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \<br>$(lsb_release -cs) stable&quot; | sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null</pre><p>This command is adding a Docker repository configuration to the “/etc/apt/sources.list.d/docker.list” file on a Debian-based system, specifically for Ubuntu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*rNPDwEmk7EJLSscIvRcYug.png" /></figure><p>Ø Update apt package again</p><pre>sudo apt-get update</pre><p>This command uses apt-get to update the local package database on your system. When you run sudo apt-get update, it checks the configured package repositories for any changes, such as new packages or updates to existing ones. It doesn’t install or upgrade packages; it only updates the information about the available packages.</p><p>Ø Install Docker Engine.</p><pre>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><p>When you run the above command, you are installing the main components of Docker, along with additional plugins that enhance Docker’s capabilities. This enables you to build, run, and manage containers on your system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Jwki3MbKgzK-0IEawwrwKg.png" /></figure><p>Ø Start and Enable Docker</p><pre>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*HAS6r_5islkz8LjI6dFqhg.png" /></figure><p>Ø Check Docker status</p><pre>sudo systemctl status docker</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*zpeZld1Yw5FH4yOTlgO49g.png" /></figure><p>Press <strong>Ctrl +C</strong> to exit or get back to the shell.</p><p>Ø Identify the user ID of user that will run the container</p><pre>id</pre><p>Ø Add the above user to the docker group</p><pre>sudo usermod -aG docker ubuntu</pre><p>Ø Check Docker Version</p><pre>docker - version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*MfZjP7nV5wp05HHsOOOb6A.png" /></figure><p>Ø Now log in as root user.</p><pre>sudo -i</pre><p>Ø Now configure AWS CLI again using aws configure</p><pre>aws configure</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ESpwiSZkxspSEPi3Tc9WZg.png" /></figure><p><strong>Note: Reconfigure the Keys again for your root user</strong></p><p><strong>1.5 Installing AWS Copilot</strong></p><p>AWS Copilot is an open-source command line interface that makes it easy for developers to build, release, and operate production-ready containerized applications on AWS App Runner, Amazon ECS, and AWS Fargate.</p><p><strong>Note:</strong> Make sure to use the Root user at this step. Run <strong><em>sudo -i </em></strong>After switching to the root user, check the AWS CLI version using <strong><em>aws — version</em></strong>, Docker version using <strong><em>docker — version,</em></strong> and AWS Access keys &amp; secrete access keys using <strong><em>aws configure</em></strong> (If the key is not configured as root user, configure them again).</p><p>Ø Now copy the below command and paste it to your EC2 machine (Ubuntu VM)</p><pre>curl -Lo copilot https://github.com/aws/copilot-cli/releases/latest/download/copilot-linux &amp;&amp; chmod +x copilot &amp;&amp; sudo mv copilot /usr/local/bin/copilot &amp;&amp; copilot - help</pre><p>This command downloads, sets permissions, moves, and then executes tThis command downloads, sets permissions, moves, and then executes the AWS Copilot CLI on your system, providing you with information about how to use it. The AWS Copilot CLI is a tool for building, releasing, and operating production-ready containerized applications on Amazon ECS (Elastic Container Service).</p><p><em>This will take around 5–10 minutes to run this command</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*F01i87wPKP_WvSmsfK8xxg.png" /></figure><p>Ø Now Clone the git repository which has all the codes in it.</p><pre>git clone https://github.com/awslabs/amazon-ecs-nodejs-microservices.git</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*pezoCFEUI4_KMRuHY51MPg.png" /></figure><p>when you run git clone <a href="https://github.com/awslabs/amazon-ecs-nodejs-microservices.git,">https://github.com/awslabs/amazon-ecs-nodejs-microservices.git,</a> you are creating a local copy of the Amazon ECS Node.js Microservices sample application on your machine. This is often the first step when working with a Git repository, as it fetches all the files and version history from the remote repository to your local system. After running this command, you will have a local directory named “amazon-ecs-nodejs-microservices” containing the code and other files from the GitHub repository.</p><p><strong>Now we have cloned it successfully, let’s proceed to the next steps.</strong></p><p><strong>2. CONTAINARIZE AND DEPLOY THE MONOLITH:</strong></p><p>Containerizing and deploying a monolith involves packaging your entire application and its dependencies into a container, making it portable and easy to deploy across different environments.</p><p>Amazon ECS (Elastic Container Service) is a service provided by AWS that helps you manage and deploy containers at scale. It abstracts away the complexities of managing the underlying infrastructure, allowing you to focus on your application.</p><p>This process provides a scalable and manageable way to run your monolith in a containerized environment. It enhances flexibility, and resource utilization, and eases deployment and updates.</p><p>In this Step, you will use Amazon ECS to instantiate a managed cluster of EC2 compute instances and deploy your image as a container running on the cluster.</p><p><em>These Steps will take around 30–45 minutes to complete</em></p><p><strong>2.1 Create an AWS Copilot Application:</strong></p><p>An AWS Copilot Application is a group of services and environments. Think of it as a label for what you are building. In this example, it’s an API built as a monolithic Node.js application. In this step, you will create a new empty application. In the terminal or command prompt, enter the following and name the Application <strong>api.</strong></p><p>Ø Now run these commands in your CLI</p><pre>cd ./amazon-ecs-nodejs-microservices/<br>copilot app init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*9Mm1Hd0NBeNNNTEzCUiuWw.png" /></figure><p>● An AWS Copilot Application creates an empty application that consists of roles to administrate StackSets, ECR repositories, KMS keys, and S3 buckets. It also creates a local directory in your repository to hold configuration files for your application and services.</p><p><strong>2.2 Create the Environment:</strong></p><p>Copilot Environments are infrastructures where applications run. AWS Copilot provides a secure VPC, an Amazon ECS cluster, a Load Balancer, and all the other resources required by the application. Enter <strong>copilot env init</strong> and choose <strong>profile default</strong> to use your AWS credentials. Name the Environment <strong>API.</strong></p><p>Ø Now Run the below command</p><pre>copilot env init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*htEqkx1wbsLFgV-UxL_dxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*xqcn_J6YbSeJsnvyAUG6fQ.png" /></figure><p>This command initializes an environment within the AWS Copilot application. It uses the Copilot CLI to initialize a new environment for your application.</p><p>Choose <strong>Yes, use default</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*O4MJo9ATXP2yy2zisvHVgA.png" /></figure><p>AWS Copilot creates a <strong>manifest.yml</strong> that is used to configure the environment.</p><p><strong>Note:</strong> If you hit the error <strong><em>Access denied: Roles may not be assumed by root account</em></strong> The error message “AccessDenied: Roles may not be assumed by root accounts” indicates that you are attempting to assume (execute) an IAM role using the root account, which is not allowed. IAM roles are designed to be assumed (executed) by IAM users, not root accounts. This is a security measure to prevent unauthorized access to AWS resources.</p><p><strong>2.3 Deploy the Environment:</strong></p><p>Ø This step is to deploy the environment and provision the services for the application. To deploy, enter <strong><em>copilot env deploy — name api </em></strong>in the terminal.</p><pre>copilot env deploy - name api</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*66DkXeb2XQnuRW6bahb1wA.png" /></figure><p><strong>2.4 Create the Monolith AWS Copilot Service:</strong></p><p>A Copilot <a href="https://aws.github.io/copilot-cli/docs/concepts/services/">Service</a> runs containers. Internet-facing services can be a Request-Driven Web Service that uses <a href="https://aws.amazon.com/apprunner/">AWS App Runner</a> or a Load Balanced Web Service that provisions an <a href="https://aws.amazon.com/elasticloadbalancing/">Application or Network Load Balancer</a> with appropriate security groups and runs on <a href="https://aws.amazon.com/ecs/">Amazon ECS</a> or <a href="https://aws.amazon.com/fargate/">Fargate</a>.</p><p>Other Service types include a Backend Service that lets AWS services communicate within the application but not to the Internet. A Worker Service is used for asynchronous service-to-service messaging with <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html">Amazon Simple Queue Service (Amazon SQS).</a></p><p>Ø This step uses a Load Balanced Web Service for the Internet-facing monolith. To create the monolithic service, enter <strong>copilot svc init</strong> and choose Load Balanced Web Service.</p><pre>copilot svc init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*UUY3fy2J85XAReqKSESMcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Jd3pI6gAZkco351GoKiidw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*DemWWzcj_yLZRDGTGZpShw.png" /></figure><p>When you run <strong>copilot svc init, </strong>Copilot will likely prompt you for information such as the service name, service type, and other configuration details specific to the service you are initializing. This command is typically used to set up a new service within your Copilot application, defining how it should be deployed, its dependencies, and any necessary configurations.</p><p>Use up and down arrows in your keyboard to select the workload type.</p><p>Ø Below is the expected output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*inHHNC0-MviUDFmmdavOcA.png" /></figure><p>Change the directory to <strong>/copilot/monolith</strong> if you are already in the <strong>amazon-ecs-nodejs-microservices </strong>directory and examine <strong><em>manifest.yml</em></strong> to see how the service is configured. Note that the parameter <strong>http</strong> defines the path for the app. The Node.js application, server.js, defines the base route as <strong>/.</strong></p><pre>cd copilot/monolith</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*1JHw3rT7UzN_8WjTZKQb-g.png" /></figure><p><strong>2.5 Deploy the Monolith AWS Copilot Service</strong></p><p>To deploy the monolith Service, enter <strong>copilot svc deploy — name monolith</strong> in the terminal. When you deploy the service, the container is built locally by Docker and pushed to your Elastic Container Registry. The service pulls the container from the registry and deploys it in the environment. The <strong>monolith </strong>application is running when the deployment is complete.</p><p>Ø Run the below command to deploy the monolith service.</p><pre>copilot svc deploy -- name monolith</pre><p>The expected output is below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qa8h5ZlNKMfLV3wOI3JVWA.png" /></figure><p><strong>2.6 Confirm the Deployment:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*kFuKXnSJPpFKb3TfzmQHCA.png" /></figure><p>Ø When deployment completes, AWS Copilot prints the URL to the service in the output.</p><p>Ø You can access your service using the load balancer link as shown below</p><h3>2.6.1 Testing Using Web:</h3><p>You can test the application deployment by entering queries in a browser, such as:</p><p><strong>Try with the different URLs (replace /number):</strong></p><p><strong>(Change the application string, region according to your deployment)</strong></p><ol><li><a href="http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/users/3"><strong>http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/users/3</strong></a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*xOY4XzMvoNo7Sq2EyAV2VQ.png" /></figure><p><strong>2)</strong> <a href="http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/threads/2"><strong>http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/threads/2</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*JIRrjp_eXWFAMoLLms47NQ.png" /></figure><p><strong>3)</strong> <a href="http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/posts/"><strong>http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/posts/</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*TI-cm4hohVdlMTT4GWYsgg.png" /></figure><p><strong>4)</strong> <a href="http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/posts/in-thread/1"><strong>http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/posts/in-thread/1</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*bFtAbnvX5X1TKmzTDac7Qg.png" /></figure><p><strong>2.6.2 Testing Using Console:</strong></p><p><strong>a)</strong> <strong>Load Balancer</strong> — The load balancer distributes requests across all available ports.</p><p><strong>b) Client</strong> — The client makes a request over port 80 to the load balancer.</p><p>c) <strong>Target Groups</strong> — Instances are registered in the application’s target group.</p><p><strong>d)Container Ports</strong> — Each container runs a single application process that binds the Node.js cluster parent to port 80 within its namespace.</p><p><strong>e)Containerized Node.js Monolith</strong> — The Node.js cluster parent is responsible for distributing traffic to the workers within the monolithic application. This architecture is containerized, but still monolithic because each container has all the same features as the rest of the containers.</p><p><strong>3. BREAK THE MONOLITH:</strong></p><p>In this module, you will break the Node.js application into several interconnected services and create an AWS Copilot Service for each microservice.</p><p>The final application architecture uses Amazon ECS and the Application Load Balancer (ALB).</p><p><em>These Steps will take around 20–30 minutes to complete.</em></p><p><strong>3.1 Create the Services<em>:</em></strong></p><p>In the previous Step, we created and deployed the<strong> api</strong> Application and the<strong> </strong><em>api</em> Environment. We can reuse these to deploy microservices. In this Step, the code for the application has been divided into three microservices: posts, threads, and users. Each one will be deployed as a service. The <strong>monolith </strong>service was deployed using the CLI menu. In this step, you can deploy services by specifying the <a href="https://aws.github.io/copilot-cli/docs/commands/svc-init/">flags</a> for the <strong>copilot svc init</strong> command. Create the <strong>post</strong> microservice first.</p><p>Ø Run the command below</p><pre>copilot svc init - app api - dockerfile ./3-microservices/services/posts/Dockerfile - name posts - svc-type &quot;Load Balanced Web Service&quot;</pre><p>This command initializes a new service named “<strong>posts”</strong> within the Copilot application named <strong>“api.”</strong> Let’s break down the components of the command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*71NcfsGgKzWpfVzKkjFkJQ.png" /></figure><p>Ø Repeat for <strong>threads </strong>and <strong>users</strong> microservices.</p><pre>copilot svc init - app api - dockerfile ./3-microservices/services/threads/Dockerfile - name threads - svc-type &quot;Load Balanced Web Service&quot;</pre><pre>copilot svc init - app api - dockerfile ./3-microservices/services/users/Dockerfile - name users - svc-type &quot;Load Balanced Web Service&quot;</pre><p>Ø Expected Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*_wzfhc03UCICix08SALhCg.png" /></figure><p><strong>3.2 Edit the path in the manifest.yml for each MicroService</strong></p><p>AWS Copilot sets the path to a Service based on the Service name. However, the route to the microservice in <strong>server.js is api/&lt;service name&gt;.</strong> Edit the path in each microservice manifest, and add <strong>api/</strong> to the path.</p><p>1. Run ls -l command. When you run ls -l, you’ll see a detailed listing of the files and directories in the current working directory. Then run cd ./copilot. It changes the current working directory to the “copilot” directory. The cd command stands for “change directory,” and it is used to navigate through the file system.</p><pre>ls -l<br>cd ./copilot<br>ls -l</pre><p>2. Now we need to update the path under the <strong>manifest.yml</strong> file for posts, threads, and users. We are doing this for <strong>posts </strong>first.</p><pre>cd ./posts<br>ls -l</pre><p>3. Now to edit the manifest.yml file we are using the vi command and click on enter.</p><pre>vi manifest.yml</pre><p>With the help of downward key, come to the desired location and update the <strong>path</strong>, replace <strong>‘/’</strong> with the <strong>‘api/post’</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*embMEH67haOftGAJdVGxtg.png" /></figure><p>Press esc and i to enter into insert mode.Change the ‘posts’ with ‘api/posts’.</p><p>4. Now press <strong>esc and :wq! To save and exit.</strong></p><p>5. Now do that for <strong>threads.</strong></p><pre>cd ./threads<br> vi manifest.yml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*iUfoUffJn9i0gEp3cXJaQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*EAl0UaSEvrNWbRw1eVBVmA.png" /></figure><p>With the help of downward key, come to the desired location and update the <strong>path</strong>, replace <strong>‘/’</strong> with the <strong>‘api/threads’</strong></p><p>6. Now do that for <strong>users.</strong></p><pre>cd ./users<br> vi manifest.yml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*PAykUchTqUwItQoKi_4pLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*LRPuTqEUZcAGOri_7z4S_w.png" /></figure><p>With the help of downward key, come to the desired location and update the <strong>path</strong>, replace <strong>‘/’</strong> with the <strong>‘api/users’</strong></p><p><strong>4. DEPLOY MICROSERVICES</strong></p><p>In this step, you will deploy your Node.js application as a set of interconnected services behind an Application Load Balancer (ALB). Then, you will delete the monolith service to seamlessly shift traffic from the monolith to the microservices. This is the process of deploying the microservices and safely transitioning the application’s traffic away from the monolith. <em>These Steps will take around 30–45 minutes to complete.</em></p><p><strong>4.1 Deploy the Microservices:</strong></p><p>For each microservice, enter <strong>copilot svc deploy — name &lt;microservice&gt;</strong>. As with the monolith service, AWS Copilot builds a container for the microservice, pushes it to a repository, and deploys it on an Amazon ECS cluster running on Fargate.</p><p>1.Run the below command</p><pre>copilot svc deploy - name posts</pre><p>Expected output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*SVBW3QowrxRuhgOa2v1ZKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ao5UEmOZUxQ6DWLvSF4UbQ.png" /></figure><p>Now you can access your service at the load balancer link, paste the link from the output to over the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*kJw5uj1wl-4VXxrrjHAHOw.png" /></figure><p>2. Deploy the<strong> threads</strong> and <strong>users</strong> microservices.</p><pre>copilot svc deploy - name threads</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*GXowCsXVUpsyQwApTcMKtg.png" /></figure><p>This command, <strong>copilot svc deploy — name threads</strong>, deploys the Copilot service named “threads” running copilot svc deploy — name threads initiates the deployment of the “threads” service, making it available and operational in the specified environment within your Copilot application.</p><p>4.Expected output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*k3TqgI7ZICpozshdb6VOWw.png" /></figure><p>5.Now you can access your service at the load balancer link, paste the link from the output to over the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*v79lyyMeTrYxbpU0nJei-w.png" /></figure><p>6.Deploy the<strong> users</strong> microservices.</p><pre>copilot svc deploy - name users</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*VIKgFNno1UXTjz_vLhHR4A.png" /></figure><p>This command, <strong>copilot svc deploy — name users</strong>, deploys the Copilot service named “users” running copilot svc deploy — name users initiate the deployment of the “users” service, making it available and operational in the specified environment within your Copilot application.</p><p>7.Expected Output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*oZwNg9aV_-XDKfDxLTeR8w.png" /></figure><p>8.Now you can access your service at the load balancer link, and paste the link from the output to over the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*MoXTxkGAx4rmrOjbFbmLnw.png" /></figure><p><strong>4.2 Shutdown the Monolith:</strong></p><p>To shut down the monolith service, delete the monolith Service. Enter <strong>copilot svc delete — name monolith</strong> in the terminal and enter y.</p><p>copilot svc delete — name monolith</p><p>Expected output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Y79ta5m--TUqI16sl5wPSQ.png" /></figure><p><strong>4.3 Verify the Deployment:</strong></p><p>You can use the previous requests to verify that the microservices are deployed and working correctly.</p><ol><li><a href="http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/users/3">http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/users/3</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*jFZJ4iu-V2gVDBRImiVxbg.png" /></figure><p>2) <a href="http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/threads/2">http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/threads/2</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Bekq1X1tMgipga-E87c9Bg.png" /></figure><p>3) <a href="http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/posts">http://api-ap-publi-pjqzwhzy6uuc-1240803606.us-west-2.elb.amazonaws.com/api/posts</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*-uNy8F0-zT69mazatVGhyg.png" /></figure><p><strong>4. </strong>Now Check using the AWS Console<strong>.</strong></p><p><strong>a) Switch the Traffic </strong>— This is the starting configuration. The monolithic Node.js app is running in a container on Amazon ECS.</p><p>b) <strong>Start Microservices </strong>— Using the three container images built and pushed to Amazon ECR by AWS Copilot, you will start up three microservices on your existing Amazon ECS cluster.</p><p><strong>5. CLEANUP THE RESOURCES:</strong></p><p>In this step, we will clean up the resources that you deployed in previous modules.</p><p>The best practice is to delete resources when the tutorial is complete to avoid ongoing charges for running services. However, you may wish to keep the resources and services deployed for a detailed examination of the infrastructure or as a template for future deployments.</p><p><em>This Step will take around 10–20 minutes to complete</em></p><p>1. In this Step, we will <strong>terminate the resources</strong> you created during this project. You will stop the services running on Amazon ECS, delete the ALB, and delete the AWS CloudFormation stack to terminate the Amazon ECS cluster, including all underlying EC2 instances.</p><pre>copilot app delete - name api</pre><p>2. Write y and click on enter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*s4Jia5y7A7rxv4gazrfl-g.png" /></figure><p>3. Now meanwhile we can go to our AWS Console and see our resources are getting terminated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*qi6EpH30o5n3Q5Zi2zObbQ.png" /></figure><p>4. It will take around 20–30 minutes to complete the deletion of all the resources.</p><p>5. Now go to your EC2 dashboard and terminate your EC2 instance.</p><p><strong>7.CONCLUSION:</strong></p><p><strong>Congratulations!</strong> You have completed the Break a Monolithic Application into Microservices Project. You learned how to run a simple monolithic application in a Docker container, deploy the same application as microservices, and then switch traffic to the microservices without any downtime.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b3ce4c932e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Cloud Migration: A Guide to AWS Strategies ️]]></title>
            <link>https://medium.com/@Rajiya.Shaik/mastering-cloud-migration-a-guide-to-aws-strategies-%EF%B8%8F-01aac464554a?source=rss-10e98ddb953e------2</link>
            <guid isPermaLink="false">https://medium.com/p/01aac464554a</guid>
            <dc:creator><![CDATA[Rajiya Shaik]]></dc:creator>
            <pubDate>Wed, 15 Jan 2025 17:06:47 GMT</pubDate>
            <atom:updated>2025-01-15T17:06:47.390Z</atom:updated>
            <content:encoded><![CDATA[<p>Migrating to the cloud has become essential for businesses aiming to stay competitive in today’s digital-first world. For organizations looking to harness the scalability, cost-efficiency, and innovation of the cloud, AWS offers a range of migration strategies. These strategies are encapsulated in the <strong>7 R’s of Cloud Migration</strong>, which provide a clear roadmap for your journey.</p><p>Let’s break down the <strong>7 R’s</strong> and how they can help you transition smoothly to AWS.</p><h3>1. Rehosting (“Lift and Shift”)</h3><p><strong>Description</strong>: Rehosting is the process of moving applications to AWS with minimal or no changes. This approach is perfect for organizations looking to migrate quickly or exit on-premises data centers.</p><ul><li><strong>Ideal for</strong>: Legacy systems, large-scale migrations.</li><li><strong>Tools</strong>: AWS Migration Hub, AWS Application Migration Service (MGN), AWS Server Migration Service (SMS).</li><li><strong>Benefits</strong>: Fast, straightforward, and requires minimal upfront effort.</li></ul><h3>2. Replatforming (“Lift, Tinker, and Shift”)</h3><p><strong>Description</strong>: In this approach, small optimizations are made during the migration to improve performance or reduce costs, without changing the application’s core architecture.</p><ul><li><strong>Ideal for</strong>: Applications that can benefit from managed services without significant rework.</li><li><strong>Examples</strong>: Migrating databases to Amazon RDS or leveraging Amazon S3 for storage.</li><li><strong>Tools</strong>: AWS Database Migration Service (DMS), AWS Elastic Beanstalk.</li><li><strong>Benefits</strong>: Combines speed with cost-efficiency and performance improvements.</li></ul><h3>3. Refactoring/Re-architecting</h3><p><strong>Description</strong>: Refactoring involves rethinking the application architecture to fully leverage AWS’s cloud-native features, such as serverless computing or microservices.</p><ul><li><strong>Ideal for</strong>: Organizations focused on scalability, innovation, and cost optimization.</li><li><strong>Examples</strong>: Breaking monolithic apps into microservices using AWS Lambda, Amazon ECS, or Amazon DynamoDB.</li><li><strong>Tools</strong>: AWS CloudFormation, AWS CodePipeline.</li><li><strong>Benefits</strong>: Unlocks long-term cost savings, better scalability, and innovation opportunities.</li><li><strong>Challenges</strong>: Requires significant effort and upfront investment.</li></ul><h3>4. Repurchasing</h3><p><strong>Description</strong>: Involves replacing an existing application with a new, often SaaS-based, solution. This eliminates the need to manage infrastructure or applications directly.</p><ul><li><strong>Ideal for</strong>: Simplifying operations and focusing on business outcomes.</li><li><strong>Examples</strong>: Moving CRM to Salesforce or adopting SAP S/4HANA on AWS.</li><li><strong>Benefits</strong>: Reduces maintenance and operational overhead.</li><li><strong>Challenges</strong>: Data migration and user retraining may be required.</li></ul><h3>5. Retiring</h3><p><strong>Description</strong>: Decommissioning outdated or redundant applications that no longer provide value.</p><ul><li><strong>Ideal for</strong>: Reducing costs and simplifying the IT landscape.</li><li><strong>Tools</strong>: AWS Cost Explorer and AWS Migration Hub to identify unused or underutilized resources.</li></ul><h3>6. Retaining</h3><p><strong>Description</strong>: Some applications are retained in their current environment due to compliance, latency, or technical constraints.</p><ul><li><strong>Ideal for</strong>: Applications not yet ready for migration or requiring on-premises solutions.</li><li><strong>Examples</strong>: Utilizing AWS Outposts for hybrid setups while keeping specific workloads on-premises.</li></ul><h3>7. Relocating</h3><p><strong>Description</strong>: Relocating involves moving an entire environment or data center to AWS without changing the application architecture. This often leverages VMware Cloud on AWS for a seamless transition.</p><ul><li><strong>Ideal for</strong>: Businesses seeking to migrate quickly while maintaining existing configurations.</li><li><strong>Examples</strong>: Migrating virtual machines from an on-premises VMware environment to VMware Cloud on AWS.</li><li><strong>Tools</strong>: VMware Cloud on AWS, AWS Migration Hub.</li><li><strong>Benefits</strong>: Simplifies migration while maintaining familiarity with existing tools and configurations.</li></ul><h3>AWS Tools for Migration</h3><p>AWS provides a comprehensive set of tools to facilitate every migration strategy:</p><ul><li><strong>AWS Migration Hub</strong>: Centralized migration tracking.</li><li><strong>AWS DMS (Database Migration Service)</strong>: Migrate databases with minimal downtime.</li><li><strong>AWS SMS (Server Migration Service)</strong>: Simplify server migrations.</li><li><strong>AWS Snow Family</strong>: Move large-scale data securely with Snowball or Snowmobile.</li></ul><h3>Best Practices for AWS Migration</h3><ol><li><strong>Assess and Plan</strong>: Use AWS Application Discovery Service to evaluate your existing infrastructure.</li><li><strong>Automate Processes</strong>: Leverage AWS tools for repeatable, efficient migrations.</li><li><strong>Adopt Incrementally</strong>: Start with smaller, less critical workloads before moving mission-critical systems.</li><li><strong>Optimize Post-Migration</strong>: Continuously fine-tune costs and performance using AWS-native services.</li></ol><h3>Conclusion</h3><p>The <strong>7 R’s of AWS Migration</strong> provide a structured approach to transitioning to the cloud, whether you’re aiming for a simple lift-and-shift or a complete re-architecture. By choosing the strategy that best fits your needs, and leveraging AWS’s suite of migration tools, you can unlock new levels of scalability, efficiency, and innovation for your business.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01aac464554a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Importance of Manual Testing in Terraform]]></title>
            <link>https://medium.com/@Rajiya.Shaik/the-importance-of-manual-testing-in-terraform-888602244a4f?source=rss-10e98ddb953e------2</link>
            <guid isPermaLink="false">https://medium.com/p/888602244a4f</guid>
            <dc:creator><![CDATA[Rajiya Shaik]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 14:25:08 GMT</pubDate>
            <atom:updated>2024-09-23T14:25:08.909Z</atom:updated>
            <content:encoded><![CDATA[<p>Terraform makes deploying and managing infrastructure repeatable and predictable. But mistakes can still happen — whether it’s due to human error, unintentional misconfigurations, or unforeseen edge cases. Manual testing adds a layer of validation that is crucial to preventing infrastructure issues before they become expensive problems.</p><h4>1. Catch Misconfigurations Early</h4><p>Automated tests are great at catching known issues, but they often can’t detect more subtle or complex problems that may arise from misconfigured resources. For instance, you may have automated tests that verify basic configurations such as the existence of a VPC or an EC2 instance. However, they may miss important details like misconfigured security groups or IAM roles with overly permissive policies.</p><p><strong>Example</strong>: Suppose a Terraform configuration creates an S3 bucket but inadvertently makes it publicly accessible due to a misconfigured policy. Manual testing would involve reviewing these security settings in greater detail, ensuring the correct policies are applied before deployment.</p><h4>2. Handling Complex Infrastructure Scenarios</h4><p>Modern cloud infrastructures are complex, often involving multiple components like load balancers, auto-scaling groups, databases, and more. While automated testing can validate many aspects of your infrastructure, some scenarios are too complex to automate entirely. This is where manual testing comes in.</p><p><strong>Example</strong>: In a multi-region deployment, manually testing failover scenarios or ensuring network configurations between regions are correct is essential. While automation can check if resources exist, manual testers can simulate failure conditions and ensure disaster recovery procedures work as expected.</p><h4>3. Verifying Infrastructure Changes</h4><p>Terraforms plan command helps by showing you what changes will be made to your infrastructure, but it doesn’t always capture the nuances of those changes. Manual testing helps to ensure that the proposed changes behave as expected in the real world.</p><p><strong>Example</strong>: Imagine updating the instance size of an EC2 cluster to improve performance. While Terraform may reflect that the instance type will change from t2.micro to t3.medium, manual testing would involve verifying that these new instances indeed perform better, without introducing new issues like unexpected cost increases or degraded performance.</p><h4>4. Ensuring Compliance and Security</h4><p>Automated security scans and checks are crucial, but they can miss subtle vulnerabilities or misconfigurations. When working with sensitive data or regulated environments (e.g., PCI-DSS, HIPAA, GDPR), manual testing is essential for ensuring that the infrastructure is secure and compliant.</p><p><strong>Example</strong>: After running Terraform to provision resources, a manual tester could review IAM policies, ensure encryption is properly enabled on storage resources, and confirm that all security group rules follow the principle of least privilege.</p><h3>Best Practices for Manual Testing in Terraform</h3><p>To maximize the value of manual testing in your Terraform workflow, follow these best practices:</p><h4>1. Review Terraform Plan Thoroughly</h4><p>Before applying changes, always review the terraform plan output to ensure that the proposed modifications are aligned with the intended goals. Look for any unexpected changes, such as resource destruction or modification of critical services.</p><h4>2. Test Critical Infrastructure Manually</h4><p>Focus your manual testing efforts on critical infrastructure components like load balancers, databases, security groups, and networking. Ensure these components are configured correctly and can handle real-world traffic and failover scenarios.</p><h4>3. Use Staging Environments</h4><p>Always perform manual testing in a staging environment before making changes to production infrastructure. This helps to catch potential issues without impacting live systems.</p><h4>4. Combine Automated and Manual Testing</h4><p>Leverage the strengths of both manual and automated testing. Use automated tests to validate known conditions and configurations while relying on manual testing for edge cases, exploratory testing, and compliance checks.</p><h4>5. Document the Manual Testing Process</h4><p>Create clear documentation for manual testing procedures, especially for complex infrastructure components. This ensures that future testing efforts are consistent and follow best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888602244a4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Docker Containers in AWS Using Elastic Kubernetes Service]]></title>
            <link>https://medium.com/@Rajiya.Shaik/deploying-docker-containers-in-aws-using-elastic-kubernetes-service-ab5ef9639ad1?source=rss-10e98ddb953e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab5ef9639ad1</guid>
            <dc:creator><![CDATA[Rajiya Shaik]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 17:52:23 GMT</pubDate>
            <atom:updated>2024-09-17T17:52:23.637Z</atom:updated>
            <content:encoded><![CDATA[<p>Most cloud providers offer managed Kubernetes services, where they run the control plane and worker nodes for you: e.g., Elastic Kubernetes Service (EKS) in AWS, Azure Kubernetes Service (AKS) in Azure, and Google Kubernetes Engine (GKE) in Google Cloud.</p><p>In this blog, I’m going to show you how to deploy a very basic EKS cluster in AWS.</p><p>Steps:</p><ol><li>Create a module in <strong><em>modules/services/eks-cluster </em></strong>and define the API for the module in a<strong><em> variables.tf</em></strong> file with the following input variables. This code exposes input variables to set the EKS cluster’s name, size, and the types of instances to use for the worker nodes.</li></ol><pre><br>variable &quot;name&quot; {<br>  description = &quot;The name to use for the EKS cluster&quot;<br>  type        = string<br>}<br><br>variable &quot;min_size&quot; {<br>  description = &quot;Minimum number of nodes to have in the EKS cluster&quot;<br>  type        = number<br>}<br><br>variable &quot;max_size&quot; {<br>  description = &quot;Maximum number of nodes to have in the EKS cluster&quot;<br>  type        = number<br>}<br><br>variable &quot;desired_size&quot; {<br>  description = &quot;Desired number of nodes to have in the EKS cluster&quot;<br>  type        = number<br>}<br><br>variable &quot;instance_types&quot; {<br>  description = &quot;The types of EC2 instances to run in the node group&quot;<br>  type        = list(string)<br>}</pre><p>2. Define <strong><em>modules/services/eks-cluster/main.tf .</em></strong></p><p>*Create an IAM role for the control plane. This IAM role can be assumed by the EKS service, and it has a Managed IAM Policy attached that gives the control plane the permissions it needs.</p><pre># Create an IAM role for the control plane<br>resource &quot;aws_iam_role&quot; &quot;cluster&quot; {<br>  name = &quot;${var.name}-cluster-role&quot;<br>  assume_role_policy = data.aws_iam_policy_document.cluster_assume_role.json<br>}<br># Allow EKS to assume the IAM role<br>data &quot;aws_iam_policy_document&quot; &quot;cluster_assume_role&quot; {<br>  statement {<br>   effect = &quot;Allow&quot;<br>   actions = [&quot;sts:AssumeRole&quot;]<br>   principals {<br>     type = &quot;Service&quot;<br>     identifiers = [&quot;eks.amazonaws.com&quot;]<br>  }<br> }<br>}<br># Attach the permissions the IAM role needs<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;AmazonEKSClusterPolicy&quot; {<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEKSClusterPolicy&quot;<br>  role = aws_iam_role.cluster.name<br>}</pre><p>*Now, add the aws_vpcand aws_subnets data sources to fetch information about the Default VPC and its subnets.</p><pre>data &quot;aws_vpc&quot; &quot;default&quot; {<br>  default = true<br>}<br>data &quot;aws_subnets&quot; &quot;default&quot; {<br>  filter {<br>  name = &quot;vpc-id&quot;<br>  values = [data.aws_vpc.default.id]<br> }<br>}</pre><p>*Now you can create the control plane for the EKS cluster by using the aws_eks_cluster resource. The preceding code configures the control plane to use the IAM role you just created, and to deploy into the Default VPC and subnets.</p><pre>resource &quot;aws_eks_cluster&quot; &quot;cluster&quot; {<br>  name = var.name<br>  role_arn = aws_iam_role.cluster.arn<br>  version = &quot;1.30&quot;<br>  vpc_config {<br>  subnet_ids = data.aws_subnets.default.ids<br>}<br># Ensure that IAM Role permissions are created before and deleted after<br># the EKS Cluster. Otherwise, EKS will not be able to properly delete<br># EKS managed EC2 infrastructure such as Security Groups.<br> depends_on = [<br>  aws_iam_role_policy_attachment.AmazonEKSClusterPolicy<br> ]<br>}</pre><p>*EKS supports several different types of worker nodes:</p><p>-self-managed EC2 Instances (e.g., in an ASG that you create),</p><p>-AWS-managed EC2Instances (known as a managed node group),</p><p>-Fargate (serverless).</p><p>Here, you use the managed node groups.</p><p>To deploy a managed node group, you first need to create another IAM role. This IAM role can be assumed by the EC2 service , and it has several Managed IAM Policies attached that give the managed node group the permissions it needs.</p><pre># Create an IAM role for the node group<br>resource &quot;aws_iam_role&quot; &quot;node_group&quot; {<br>  name = &quot;${var.name}-node-group&quot;<br>  assume_role_policy = data.aws_iam_policy_document.node_assume_role.json<br>}<br># Allow EC2 instances to assume the IAM role<br>data &quot;aws_iam_policy_document&quot; &quot;node_assume_role&quot; {<br>  statement {<br>  effect = &quot;Allow&quot;<br>  actions = [&quot;sts:AssumeRole&quot;]<br>  principals {<br>   type = &quot;Service&quot;<br>   identifiers = [&quot;ec2.amazonaws.com&quot;]<br>  }<br> }<br>}<br><br># Attach the permissions the node group needs<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;AmazonEKSWorkerNodePolicy&quot; {<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy&quot;<br>  role = aws_iam_role.node_group.name<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;AmazonEC2ContainerRegistryReadOnly&quot; {<br> policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly&quot;<br> role = aws_iam_role.node_group.name<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;AmazonEKS_CNI_Policy&quot; {<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy&quot;<br>  role = aws_iam_role.node_group.name<br>}</pre><p>*Now you can use the aws_eks_node_group resource to create the managed node group itself. This code configures the managed node group to use the control plane and IAM role you just created, to deploy into the Default VPC, and to use the name, size, and instance type parameters passed in as input variables.</p><pre>resource &quot;aws_eks_node_group&quot; &quot;nodes&quot; {<br>  cluster_name = aws_eks_cluster.cluster.name<br>  node_group_name = var.name<br>  node_role_arn = aws_iam_role.node_group.arn<br>  subnet_ids = data.aws_subnets.default.ids<br>  instance_types = var.instance_types<br>  scaling_config {<br>  min_size = var.min_size<br>  max_size = var.max_size<br>  desired_size = var.desired_size<br>}<br># Ensure that IAM Role permissions are created before and deleted after<br># the EKS Node Group. Otherwise, EKS will not be able to properly<br># delete EC2 Instances and Elastic Network Interfaces.<br> depends_on = [<br>  aws_iam_role_policy_attachment.AmazonEKSWorkerNodePolicy,<br>  aws_iam_role_policy_attachment.AmazonEC2ContainerRegistryReadOnly,<br>  aws_iam_role_policy_attachment.AmazonEKS_CNI_Policy,<br>]<br>}</pre><p>3. Define <strong><em>modules/services/eks-cluster/outputs.tf</em></strong></p><pre>output &quot;cluster_name&quot; {<br>  value = aws_eks_cluster.cluster.name<br>  description = &quot;Name of the EKS cluster&quot;<br>}<br>output &quot;cluster_arn&quot; {<br>  value = aws_eks_cluster.cluster.arn<br>  description = &quot;ARN of the EKS cluster&quot;<br>}<br>output &quot;cluster_endpoint&quot; {<br>  value = aws_eks_cluster.cluster.endpoint<br>  description = &quot;Endpoint of the EKS cluster&quot;<br>}<br>output &quot;cluster_certificate_authority&quot; {<br>  value = aws_eks_cluster.cluster.certificate_authority<br>  description = &quot;Certificate authority of the EKS cluster&quot;<br>}</pre><p>4. Create <strong><em>examples/kubernetes-eks/main.tf</em></strong>, and configure the eks-cluster module as follows.</p><pre>provider &quot;aws&quot; {<br> region = &quot;us-east-2&quot;<br>}<br>module &quot;eks_cluster&quot; {<br>  source = &quot;../../modules/services/eks-cluster&quot;<br>    name = &quot;example-eks-cluster&quot;<br>    min_size = 1<br>    max_size = 2<br>    desired_size = 1<br># Due to the way EKS works with ENIs, t3.small is the smallest<br># instance type that can be used for worker nodes. If you try<br># something smaller like t2.micro, which only has 4 ENIs,<br># they&#39;ll all be used up by system services (e.g., kube-proxy)<br># and you won&#39;t be able to deploy your own Pods.<br>  instance_types = [&quot;t3.small&quot;]<br>}</pre><p>* Next, configure the<strong><em> k8s-app</em></strong> module as follows. The preceding code configures the Kubernetes provider to authenticate to the EKS cluster. It then uses the<strong><em> k8s-app</em></strong> module to deploy the <strong><em>training/webapp </em></strong>Docker image</p><pre>provider &quot;kubernetes&quot; {<br>  host = module.eks_cluster.cluster_endpoint<br>  cluster_ca_certificate = base64decode(<br>    module.eks_cluster.cluster_certificate_authority[0].data<br>)<br>  token = data.aws_eks_cluster_auth.cluster.token<br>}<br><br>data &quot;aws_eks_cluster_auth&quot; &quot;cluster&quot; {<br>  name = module.eks_cluster.cluster_name<br>}<br><br>module &quot;simple_webapp&quot; {<br>  source = &quot;../../modules/services/k8s-app&quot;<br>    name = &quot;simple-webapp&quot;<br>    image = &quot;training/webapp&quot;<br>    replicas = 2<br>    container_port = 5000<br><br> environment_variables = {<br>    PROVIDER = &quot;Terraform&quot;<br>}<br><br># Only deploy the app after the cluster has been deployed<br>depends_on = [module.eks_cluster]<br>}</pre><p>5. <strong><em>examples/kubernetes-eks/outputs.tf. </em></strong>Next, pass through the cluster_arn cluster_endpoint service_endpoint as an output variables.</p><pre>output &quot;cluster_arn&quot; {<br>  value       = module.eks_cluster.cluster_arn<br>  description = &quot;ARN of the EKS cluster&quot;<br>}<br><br>output &quot;cluster_endpoint&quot; {<br>  value       = module.eks_cluster.cluster_endpoint<br>  description = &quot;Endpoint of the EKS cluster&quot;<br>}<br><br>output &quot;service_endpoint&quot; {<br>  value       = module.simple_webapp.service_endpoint<br>  description = &quot;The K8S Service endpoint&quot;<br>}</pre><p>6. Now run terraform init terraform plan terraform apply .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Vlw1DomBKzGa5j9K44D9g.png" /></figure><p>Wait a little while for the web app to spin up and pass health checks, and then test out the service_endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNW2mMZq0cYOvn8Fwz3E9Q.png" /></figure><p>7.Try updating environment_variables to adifferent PROVIDER value, such as “Razia-Reader!”</p><pre>module &quot;simple_webapp&quot; {<br>source = &quot;../../modules/services/k8s-app&quot;<br>name = &quot;simple-webapp&quot;<br>image = &quot;training/webapp&quot;<br>replicas = 2<br>container_port = 5000<br>environment_variables = {<br>PROVIDER = &quot;Razia-Reader!&quot;<br>}<br># Only deploy the app after the cluster has been deployed<br>depends_on = [module.eks_cluster]<br>}</pre><p>Rerun apply, and just a few seconds later, the Kubernetes Deployment will have deployed the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PB5ghQNU1k_2FPSbSG__Qg.png" /></figure><p>8. You can use kubectl again to see what’s happening in your cluster. To authenticate <strong><em>kubectl</em></strong> to the EKS cluster, you can use the aws eks update-kubeconfig command to automatically update your <strong>$HOME/.kube/config</strong> file.</p><pre>aws eks update-kubeconfig --region &lt;REGION&gt; --name &lt;EKS_CLUSTER_NAME&gt;</pre><pre>aws eks update-kubeconfig --region us-east-2 --name kubernetes-example</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cs-de8pFCAEaVOZA-21DVw.png" /></figure><p>9.you can use the <strong><em>get nodes</em></strong> command to inspect the worker nodes in your cluster.</p><pre>kubectl get nodes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kj7SfF7rjocn2_Bz8SlYnw.png" /></figure><p>10.You can use the <strong>get deployments</strong> command to inspect your Deployments.</p><pre>kubectl get deployments</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnrZEiaeIpzicrr6Icsbog.png" /></figure><p>11. Next, run get pods to see the Pods.</p><pre>kubectl get pods</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGWtxgUDcs78qt8Tqitfmg.png" /></figure><p>12. And finally, run get services to see the Services. You should be able to see your load balancer and the URL you used to test it.</p><pre>kubectl get services</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*07kAmPeF_8yhhGherQZUhA.png" /></figure><p>So here you have it: two different providers, both working in the same cloud, helping you to deploy containerized workloads.</p><p>Reference:</p><p>Terraform Up &amp; Running-Writing Infrastructure as Code</p><p>By-Yevgeniy Brikman</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab5ef9639ad1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Multi-Region Deployments with Terraform Providers]]></title>
            <link>https://medium.com/@Rajiya.Shaik/managing-multi-region-deployments-with-terraform-providers-2872b88fa720?source=rss-10e98ddb953e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2872b88fa720</guid>
            <dc:creator><![CDATA[Rajiya Shaik]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 19:23:03 GMT</pubDate>
            <atom:updated>2024-09-14T19:23:03.706Z</atom:updated>
            <content:encoded><![CDATA[<p>The following provider block configures your code to deploy to a single AWS region in a single AWS account.</p><pre>provider &quot;aws&quot; {<br>region = &quot;us-east-2&quot;<br>}</pre><p>What if you need to deploy to multiple AWS regions? For example, how could you deploy some resources into us-east-2 and other resources into us-west-1?</p><p>In this blog let’s see how you can deploy two EC2 Instances in different regions us-east-2 and us-west-1</p><p><strong>Steps:</strong></p><p>1.Add an aliasto each provider. An aliasis a custom name for the provider, which you can explicitly pass to individual resources, data sources, and modules to get them to use the configuration in that particular provider.</p><pre>provider &quot;aws&quot; {<br>  region = &quot;us-east-2&quot;<br>  alias = &quot;region_1&quot;<br>}<br>provider &quot;aws&quot; {<br>  region = &quot;us-west-1&quot;<br>  alias = &quot;region_2&quot;<br>}</pre><p>2. Specify data source for each region, which returns the current AWS region. To tell those aws_region data sources to use a specific provider, you set the provider parameter as follows.</p><pre>data &quot;aws_region&quot; &quot;region_1&quot; {<br>  provider = aws.region_1<br>}<br>data &quot;aws_region&quot; &quot;region_2&quot; {<br>  provider = aws.region_2<br>}</pre><p>3. AMI IDs are unique to each AWS region, so the ID for Ubuntu 20.04 in us-east-2is different than for Ubuntu 20.04 in us-west-1. Having to look up and manage these AMI IDs manually is tedious and error prone. Fortunately, there’s a better alternative: use the aws_amidata source that, given a set of filters, can find AMI IDs for you automatically.</p><pre>data &quot;aws_ami&quot; &quot;ubuntu_region_1&quot; {<br>  provider = aws.region_1<br>  most_recent = true<br>  owners = [&quot;099720109477&quot;] # Canonical<br>  filter {<br>  name = &quot;name&quot;<br>  values = [&quot;ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*&quot;]<br> }<br>}<br>data &quot;aws_ami&quot; &quot;ubuntu_region_2&quot; {<br>  provider = aws.region_2<br>  most_recent = true<br>  owners = [&quot;099720109477&quot;] # Canonical<br>  filter {<br>  name = &quot;name&quot;<br>  values = [&quot;ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*&quot;]<br> }<br>}</pre><p>Notice that each data source sets the provider parameter to ensure it’s looking up the AMI ID in the proper region.</p><p>4. Create resource for aws_intancein each region and update the amiparameter to use the output of these data sources instead of the hardcoded values.</p><pre>resource &quot;aws_instance&quot; &quot;region_1&quot; {<br>  provider = aws.region_1<br><br>  ami = data.aws_ami.ubuntu_region_1.id<br>  instance_type = &quot;t2.micro&quot;<br>}<br><br>resource &quot;aws_instance&quot; &quot;region_2&quot; {<br>  provider = aws.region_2<br><br>  ami = data.aws_ami.ubuntu_region_2.id<br>  instance_type = &quot;t2.micro&quot;<br>}</pre><p>5.To check that these EC2 Instances are really deploying into different regions, add output variables that show you which availability zone(each of which is in one region) each instance was actually deployed into.</p><p>outputs.tf</p><pre>output &quot;region_1&quot; {<br>  value = data.aws_region.region_1.name<br>  description = &quot;The name of the first region&quot;<br>}<br><br>output &quot;region_2&quot; {<br>  value = data.aws_region.region_2.name<br>  description = &quot;The name of the second region&quot;<br>}<br><br>output &quot;instance_region_1_az&quot; {<br>  value = aws_instance.region_1.availability_zone<br>  description = &quot;The AZ where the instance in the first region deployed&quot;<br>}<br><br>output &quot;instance_region_2_az&quot; {<br>  value = aws_instance.region_2.availability_zone<br>  description = &quot;The AZ where the instance in the second region deployed&quot;<br>}</pre><p>main.tf</p><pre>terraform {<br>  required_version = &quot;&gt;= 1.0.0, &lt; 2.0.0&quot;<br><br>  required_providers {<br>    aws = {<br>      source = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-east-2&quot;<br>  alias  = &quot;region_1&quot;<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-west-1&quot;<br>  alias  = &quot;region_2&quot;<br>}<br><br>data &quot;aws_region&quot; &quot;region_1&quot; {<br>  provider = aws.region_1<br>}<br><br>data &quot;aws_region&quot; &quot;region_2&quot; {<br>  provider = aws.region_2<br>}<br><br>resource &quot;aws_instance&quot; &quot;region_1&quot; {<br>  provider = aws.region_1<br><br>  ami           = data.aws_ami.ubuntu_region_1.id<br>  instance_type = &quot;t2.micro&quot;<br>}<br><br>resource &quot;aws_instance&quot; &quot;region_2&quot; {<br>  provider = aws.region_2<br><br>  ami           = data.aws_ami.ubuntu_region_2.id<br>  instance_type = &quot;t2.micro&quot;<br>}<br><br>data &quot;aws_ami&quot; &quot;ubuntu_region_1&quot; {<br>  provider = aws.region_1<br><br>  most_recent = true<br>  owners      = [&quot;099720109477&quot;] # Canonical<br><br>  filter {<br>    name   = &quot;name&quot;<br>    values = [&quot;ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*&quot;]<br>  }<br>}<br><br>data &quot;aws_ami&quot; &quot;ubuntu_region_2&quot; {<br>  provider = aws.region_2<br><br>  most_recent = true<br>  owners      = [&quot;099720109477&quot;] # Canonical<br><br>  filter {<br>    name   = &quot;name&quot;<br>    values = [&quot;ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*&quot;]<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VEC9LbCs1juEdw6NyrulBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yIqW131ZO3YWxUg7DKecw.png" /><figcaption>Instance in us-east-2b availability zone</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYdwGKHiAjR2LlcH1ea0Sw.png" /><figcaption>Instance in us-west-1c availability zone</figcaption></figure><p>Reference:</p><p>Terraform Up &amp; Running-Writing Infrastructure as Code</p><p>By-Yevgeniy Brikman</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2872b88fa720" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle Sensitive Data Securely in Terraform using AWS Secrets Manager]]></title>
            <link>https://medium.com/@Rajiya.Shaik/handle-sensitive-data-securely-in-terraform-using-aws-secrets-manager-bec5dd718c71?source=rss-10e98ddb953e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bec5dd718c71</guid>
            <dc:creator><![CDATA[Rajiya Shaik]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 16:40:29 GMT</pubDate>
            <atom:updated>2024-09-13T16:40:29.605Z</atom:updated>
            <content:encoded><![CDATA[<p>As organizations embrace Infrastructure as Code (IaC), Terraform has become one of the go-to tools for provisioning and managing cloud infrastructure. However, You may encounter secrets in your Terraform code when working with resources and data sources.</p><p>For example of passing database credentials to the aws_db_instance resource. Storing credentials in the code, as plain text, is a bad idea.</p><pre>resource &quot;aws_db_instance&quot; &quot;example&quot; {<br>  identifier_prefix = &quot;terraform-up-and-running&quot;<br>  engine = &quot;mysql&quot;<br>  allocated_storage = 20<br>  instance_class = &quot;db.t3.micro&quot;<br>  skip_final_snapshot = true<br>  db_name = var.db_name<br><br># DO NOT DO THIS!!!<br>  username = &quot;admin&quot;<br>  password = &quot;password&quot;<br># DO NOT DO THIS!!!<br>}</pre><p>The better way to do it is using</p><p><strong>Environment variables</strong>- Passing in secrets via environment variables helps you avoid storing secrets in plain text in your code.</p><p><strong>Encrypted files</strong>-To encrypt data like secrets in a file, you need an encryption key, which is also a secret. A common solution is to store it securely using your cloud provider’s KMS (e.g., AWS KMS, Google KMS, Azure Key Vault) or PGP keys from team members.</p><p><strong>Secret stores- </strong>You can store your secrets in a centralized secret store like AWS Secrets Manager, Google Secret Manager, Azure Key Vault, and Hashi Corp Vault.</p><p>In this blog, let’s understand how to store your database credentials in AWS Secrets Manager and use those credentials for creating a database instance.</p><p><strong>Steps:</strong></p><ol><li>Open AWS Management Console, search for AWS Secrets Manager and click on create new secret .</li><li>Select the secret type other type of secrets and specify the key/value pairs stored in the secret in the plain text. Note that the secrets are in a JSON format, which is the recommended format for storing data in AWS Secrets Manager.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m0q4u2vW7neA65NWUlLbUg.png" /><figcaption>Store secrets in JSON format in AWS Secrets Manager</figcaption></figure><p>3.Go to the next step, and make sure to give the secret a unique name, such as “db-creds”. Click Next and Store to save the secret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETzxRWhClIUxtSDH9a-M9w.png" /><figcaption>Give the secret a unique name in AWS Secrets Manager</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EM6egeIY8oMwmNCvVEYsFg.png" /></figure><p>4.Now, in your Terraform code, you can use the aws_secretsmanager_secret_versiondata source to read the db_creds secret.</p><pre>data &quot;aws_secretsmanager_secret_version&quot; &quot;creds&quot; {<br>secret_id = &quot;db-credens&quot;<br>}</pre><p>5.Since the secret is stored as JSON, you can use the jsondecode function to parse the JSON into the local variable db_creds.</p><pre>locals {<br>db_creds = jsondecode(<br>data.aws_secretsmanager_secret_version.creds.secret_string<br>)<br>}</pre><p>6.And now you can read the database credentials from db_creds and pass them into the aws_db_instance resource.</p><pre>resource &quot;aws_db_instance&quot; &quot;example&quot; {<br>  identifier_prefix = &quot;terraform-up-and-running&quot;<br>  engine = &quot;mysql&quot;<br>  allocated_storage = 20<br>  instance_class = &quot;db.t3.micro&quot;<br>  skip_final_snapshot = true<br>  db_name = var.db_name<br><br># Pass the secrets to the resource<br>  username = local.db_creds.username<br>  password = local.db_creds.password<br>}</pre><p>7.Now run the following commands.</p><p>terraform init</p><p>terraform plan</p><p>terraform apply</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTfqyNbaKbGb7hdDb6BHkw.png" /></figure><p>8. When you don’t need the resources run terraform destroy to delete your resources.</p><p>The configuration file look likes this.</p><p>Main.tf</p><pre>terraform {<br>  required_version = &quot;&gt;= 1.0.0, &lt; 2.0.0&quot;<br><br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-east-2&quot;<br>}<br><br>data &quot;aws_secretsmanager_secret_version&quot; &quot;creds&quot; {<br>  secret_id = &quot;db-credens&quot;<br>}<br><br>locals {<br>  db_creds = jsondecode (<br>    data.aws_secretsmanager_secret_version.creds.secret_string<br>  )<br>}<br><br>resource &quot;aws_db_instance&quot; &quot;example&quot; {<br>  identifier_prefix   = &quot;terraform-up-and-running&quot;<br>  engine              = &quot;mysql&quot;<br>  allocated_storage   = 20<br>  instance_class      = &quot;db.t3.micro&quot;<br>  skip_final_snapshot = true<br>  db_name             = var.db_name<br><br>  # Pass the secrets to the resource<br>  username = local.db_creds.username<br>  password = local.db_creds.password<br>}</pre><p>variables.tf</p><pre><br>variable &quot;db_name&quot; {<br>  description = &quot;The name to use for the database&quot;<br>  type        = string<br>  default     = &quot;example&quot;<br>}</pre><p>outputs.tf</p><pre>output &quot;address&quot; {<br>  value       = aws_db_instance.example.address<br>  description = &quot;Connect to the database at this endpoint&quot;<br>}<br><br>output &quot;port&quot; {<br>  value       = aws_db_instance.example.port<br>  description = &quot;The port the database is listening on&quot;<br>}</pre><p><strong>Advantages of using secret stores:</strong></p><ul><li>Keeps plain-text secrets out of code and version control.</li><li>Fully defined in code, avoiding manual steps or scripts.</li><li>Easy storage through a web UI.</li><li>Supports rotating and revoking secrets, with optional scheduled rotation.</li><li>Provides detailed audit logs for tracking data access.</li><li>Standardizes secret management with enforced encryption and access patterns.</li></ul><p><strong>Drawbacks of using secret stores:</strong></p><ul><li>Configuration errors are more likely since secrets aren’t versioned or packaged with code.</li><li>Managed secret stores can be costly (e.g., AWS Secrets Manager charges per secret and API call).</li><li>Self-managed stores, like Hashi Corp Vault, require additional infrastructure, time, and developer resources, which can be expensive.</li></ul><p>Reference:</p><p>Terraform Up &amp; Running-Writing Infrastructure as Code</p><p>By-Yevgeniy Brikman</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bec5dd718c71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Blue/Green Deployments with Terraform for Zero Downtime]]></title>
            <link>https://medium.com/@Rajiya.Shaik/how-to-implement-blue-green-deployments-with-terraform-for-zero-downtime-546f05116851?source=rss-10e98ddb953e------2</link>
            <guid isPermaLink="false">https://medium.com/p/546f05116851</guid>
            <dc:creator><![CDATA[Rajiya Shaik]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 13:08:54 GMT</pubDate>
            <atom:updated>2024-09-11T13:08:54.575Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s fast-paced digital landscape, continuous deployment and high availability are critical for maintaining user satisfaction and business success. One of the most effective deployment strategies for achieving <strong>zero downtime</strong> during infrastructure updates is <strong>Blue/Green Deployments</strong>.</p><p>In this blog, we’ll take a deep dive into what Blue/Green Deployments are, why they matter, and how to implement them using Terraform to ensure your applications stay online even during updates.</p><h3>What is Blue/Green Deployment?</h3><p><strong>Blue/Green Deployment</strong> is a strategy where two separate environments — <strong>blue</strong> and <strong>green</strong> — are maintained. At any given time, one environment (say, blue) is live and serving traffic, while the other (green) is idle and used for deploying updates or testing. Once updates are validated in the green environment, traffic is switched from blue to green, ensuring a seamless transition.</p><p>Key benefits include:</p><ul><li><strong>Zero downtime</strong>: Traffic is routed to the new environment only when it’s fully ready.</li><li><strong>Easy rollback</strong>: In case of issues, you can revert traffic back to the previous (blue) environment.</li><li><strong>Safer deployments</strong>: You can test changes in a production-like environment without affecting live users.</li></ul><h3>How Blue/Green Deployment Works</h3><p>Here’s a simplified workflow of how Blue/Green Deployments operate:</p><ol><li><strong>Blue Environment (Live)</strong>: Your current production environment, which is actively serving traffic.</li><li><strong>Green Environment (Idle)</strong>: A replica of the blue environment, used to deploy and test new updates.</li><li><strong>Deploy Changes to Green</strong>: New updates are applied to the green environment.</li><li><strong>Test the Green Environment</strong>: Validate that the new environment functions correctly.</li><li><strong>Switch Traffic to Green</strong>: Once validated, traffic is switched from blue to green, making green the new live environment.</li><li><strong>Monitor and Rollback (if needed)</strong>: Monitor the green environment and, if issues arise, you can revert to blue.</li></ol><h3>Implementing Blue/Green Deployments with Terraform</h3><p>Terraform is an excellent tool for managing Blue/Green Deployments because it allows you to define your entire infrastructure as code and automates the deployment process. Below, we’ll walk through a step-by-step guide to implementing Blue/Green Deployments using Terraform.</p><h3>Prerequisites</h3><ul><li>An account with a cloud provider like AWS, Google Cloud, or Azure.</li><li>Basic knowledge of Terraform and Infrastructure as Code (IaC).</li><li>Familiarity with load balancers, which are crucial for routing traffic between environments.</li></ul><h3>Step 1: Set Up the Blue Environment</h3><p>Let’s start by defining the blue environment in Terraform. We’ll assume an AWS setup where an <strong>Auto Scaling Group (ASG)</strong> and <strong>Elastic Load Balancer (ELB)</strong> are used to manage EC2 instances.</p><pre>resource &quot;aws_launch_configuration&quot; &quot;blue&quot; {<br>  name          = &quot;blue-lc&quot;<br>  image_id      = &quot;ami-12345678&quot;<br>  instance_type = &quot;t2.micro&quot;<br>lifecycle {<br>    create_before_destroy = true<br>  }<br>}<br>resource &quot;aws_autoscaling_group&quot; &quot;blue&quot; {<br>  desired_capacity     = 3<br>  max_size             = 3<br>  min_size             = 1<br>  vpc_zone_identifier  = [aws_subnet.main.id]<br>  launch_configuration = aws_launch_configuration.blue.id<br>  target_group_arns = [aws_lb_target_group.blue.arn]<br>}</pre><p>In this configuration:</p><ul><li>A <strong>launch configuration</strong> defines the AMI and instance type.</li><li>The <strong>Auto Scaling Group</strong> (ASG) is responsible for creating and maintaining EC2 instances.</li><li>The <strong>ELB Target Group</strong> points to the blue environment instances.</li></ul><p>This setup defines your live <strong>blue</strong> environment, which is currently serving traffic.</p><h3>Step 2: Set Up the Green Environment</h3><p>Next, we’ll define the green environment, which is an identical setup to the blue environment but serves as the idle environment where new updates will be deployed.</p><pre>resource &quot;aws_launch_configuration&quot; &quot;green&quot; {<br>  name          = &quot;green-lc&quot;<br>  image_id      = &quot;ami-87654321&quot;  # This can be a new AMI with updated code.<br>  instance_type = &quot;t2.micro&quot;<br>lifecycle {<br>    create_before_destroy = true<br>  }<br>}<br>resource &quot;aws_autoscaling_group&quot; &quot;green&quot; {<br>  desired_capacity     = 3<br>  max_size             = 3<br>  min_size             = 1<br>  vpc_zone_identifier  = [aws_subnet.main.id]<br>  launch_configuration = aws_launch_configuration.green.id<br>  target_group_arns = [aws_lb_target_group.green.arn]<br>}</pre><p>The <strong>green</strong> environment mirrors the blue environment, but it can have updated configurations like a newer AMI or different launch settings.</p><h3>Step 3: Use a Load Balancer to Switch Traffic</h3><p>A key part of the Blue/Green strategy is using a <strong>load balancer</strong> to route traffic between the two environments. Here’s how to configure a load balancer in Terraform to support both blue and green environments:</p><pre>resource &quot;aws_lb&quot; &quot;main&quot; {<br>  name               = &quot;main-lb&quot;<br>  internal           = false<br>  load_balancer_type = &quot;application&quot;<br>  security_groups    = [aws_security_group.lb_sg.id]<br>  subnets            = [aws_subnet.main.id]<br>}<br>resource &quot;aws_lb_target_group&quot; &quot;blue&quot; {<br>  name     = &quot;blue-tg&quot;<br>  port     = 80<br>  protocol = &quot;HTTP&quot;<br>  vpc_id   = aws_vpc.main.id<br>}<br>resource &quot;aws_lb_target_group&quot; &quot;green&quot; {<br>  name     = &quot;green-tg&quot;<br>  port     = 80<br>  protocol = &quot;HTTP&quot;<br>  vpc_id   = aws_vpc.main.id<br>}<br>resource &quot;aws_lb_listener&quot; &quot;http&quot; {<br>  load_balancer_arn = aws_lb.main.arn<br>  port              = 80<br>  protocol          = &quot;HTTP&quot;<br>  default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.blue.arn<br>  }<br>}</pre><p>In this configuration:</p><ul><li>The <strong>AWS Load Balancer</strong> listens on port 80 for HTTP traffic.</li><li>Two <strong>target groups</strong> (blue and green) represent the instances in the blue and green environments.</li><li>Initially, the load balancer directs traffic to the blue target group.</li></ul><h3>Step 4: Deploy and Test Changes in the Green Environment</h3><p>Once your green environment is set up, you can deploy the updated infrastructure. You should run Terraform’s apply command to create the green environment:</p><pre>terraform apply</pre><p>With the green environment up and running, you can now test the environment by manually pointing a limited set of users (or internal testing teams) to the green target group and ensuring everything works as expected.</p><h3>Step 5: Switching Traffic from Blue to Green</h3><p>Once you are confident the green environment is functioning correctly, it’s time to shift live traffic from the blue environment to the green environment. You can do this by updating the <strong>listener rule</strong> to point to the green target group:</p><pre>resource &quot;aws_lb_listener&quot; &quot;http&quot; {<br>  load_balancer_arn = aws_lb.main.arn<br>  port              = 80<br>  protocol          = &quot;HTTP&quot;<br>default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.green.arn<br>  }<br>}</pre><p>By running terraform apply, Terraform will update the listener to route all traffic to the green environment. This switchover happens almost instantly, ensuring zero downtime.</p><h3>Step 6: Monitoring and Rollback</h3><p>After the traffic has been switched to the green environment, monitor the application’s health using tools like <strong>AWS CloudWatch</strong> to track metrics such as instance health and response times. If any issues arise, you can easily revert to the blue environment by pointing the load balancer back to the blue target group:</p><pre>resource &quot;aws_lb_listener&quot; &quot;http&quot; {<br>  load_balancer_arn = aws_lb.main.arn<br>  port              = 80<br>  protocol          = &quot;HTTP&quot;<br>default_action {<br>    type             = &quot;forward&quot;<br>    target_group_arn = aws_lb_target_group.blue.arn<br>  }<br>}</pre><p>This provides a quick and reliable rollback mechanism without requiring significant infrastructure changes.</p><h3>Best Practices for Blue/Green Deployments with Terraform</h3><p>To ensure successful Blue/Green Deployments, follow these best practices:</p><ol><li><strong>Automate Health Checks</strong>: Always set up health checks to automatically verify that instances in the green environment are functioning correctly before switching traffic.</li><li><strong>Use Terraform Workspaces</strong>: If managing multiple environments (staging, production), Terraform workspaces can help separate configurations and maintain cleaner state management.</li><li><strong>Plan for Rollbacks</strong>: Always plan for a rollback scenario in case of failure. Ensure your blue environment remains intact until you’re confident the green environment is stable.</li><li><strong>Monitor the Deployment</strong>: Use monitoring tools to keep track of resource utilization, instance health, and load balancer metrics before, during, and after the traffic switch.</li></ol><h3>Conclusion</h3><p>Implementing Blue/Green Deployments with Terraform is a powerful way to ensure <strong>zero downtime</strong> during infrastructure updates. By maintaining two separate environments and carefully managing traffic with a load balancer, you can roll out new updates with confidence, knowing that your users will experience a seamless transition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=546f05116851" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Conditionals Simplify Infrastructure as Code with Terraform]]></title>
            <link>https://medium.com/@Rajiya.Shaik/how-conditionals-simplify-infrastructure-as-code-with-terraform-7444595b64fd?source=rss-10e98ddb953e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7444595b64fd</guid>
            <dc:creator><![CDATA[Rajiya Shaik]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 13:24:20 GMT</pubDate>
            <atom:updated>2024-09-10T13:24:20.050Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last blog I have discussed about <a href="https://medium.com/@sulthana.sk.1984/how-loops-simplify-infrastructure-as-code-with-terraform-b1baa0afa198">How Loops Simplify Infrastructure as Code with Terraform</a>. In this blog we dive deep into how <strong>conditionals</strong> simplify the infrastructure as code with terrafrom.</p><h4>Conditionals in Terraform</h4><p>Conditionals are essential for managing different environments, regions, or configurations based on variable values. They make your infrastructure more flexible by allowing you to define different setups based on specific conditions, such as environment (production vs. development) or region.</p><p>Terraform provides various ways to handle loops and conditionals, each suited for different scenarios:</p><ul><li><strong>Count Parameter</strong>: Ideal for creating or skipping conditional resources. It determines how many instances of a resource should be created based on a condition.</li><li><strong>For-Each and For Expressions</strong>: These are used for both conditional resources and inline blocks within a resource. They allow iteration over collections to dynamically create multiple instances.</li><li><strong>If String Directive</strong>: This is used for simple conditionals within a string, often to adjust resource attributes based on a condition.</li></ul><h3>1. The Ternary Operator-If-statements with the count parameter</h3><p>The most basic form of conditional in Terraform is the <strong>ternary operator. </strong>It allows you to return one of two values based on a condition.</p><h4>Syntax:</h4><pre>condition ? true_value : false_value</pre><p><strong>Example Use Case: Environment-Based Autoscaling</strong></p><pre>variable &quot;enable_autoscaling&quot; {<br>description = &quot;If set to true, enable auto scaling&quot;<br>type = bool<br>}<br>resource &quot;aws_autoscaling_schedule&quot; &quot;scale_out_during_business_hours&quot; {<br>count = var.enable_autoscaling ? 1 : 0<br>scheduled_action_name = &quot;${var.cluster_name}-scale-out-during-business-hours&quot;<br>min_size = 2<br>max_size = 10<br>desired_capacity = 10<br>recurrence = &quot;0 9 * * *&quot;<br>autoscaling_group_name = aws_autoscaling_group.example.name<br>}</pre><p>If var.enable_autoscaling is true, the count parameter of the</p><p>var.enable_autoscaling resources will be set to 1, so one of each will be created. If var.enable_autoscalingis false, the count parameter for each of the aws_autoscaling_scheduleresources will be set to 0, so neither one will be created.</p><h4><strong>2.The ternary operator-If-else-statements with the count parameter</strong></h4><p>Lets understand the example which provides cloudwatch full access or read-only access to the IAM user.</p><p>Here is an IAM Policy that allows read-only access to CloudWatch:</p><pre>resource &quot;aws_iam_policy&quot; &quot;cloudwatch_read_only&quot; {<br>name = &quot;cloudwatch-read-only&quot;<br>policy = data.aws_iam_policy_document.cloudwatch_read_only.json<br>}<br>data &quot;aws_iam_policy_document&quot; &quot;cloudwatch_read_only&quot; {<br>statement {<br>effect = &quot;Allow&quot;<br>actions = [<br>&quot;cloudwatch:Describe*&quot;,<br>&quot;cloudwatch:Get*&quot;,<br>&quot;cloudwatch:List*&quot;<br>]<br>resources = [&quot;*&quot;]<br>}<br>}</pre><p>And here is an IAM Policy that allows full (read and write) access to CloudWatch:</p><pre>resource &quot;aws_iam_policy&quot; &quot;cloudwatch_full_access&quot; {<br>name = &quot;cloudwatch-full-access&quot;<br>policy = data.aws_iam_policy_document.cloudwatch_full_access.json<br>}<br>data &quot;aws_iam_policy_document&quot; &quot;cloudwatch_full_access&quot; {<br>statement {<br>effect = &quot;Allow&quot;<br>actions = [&quot;cloudwatch:*&quot;]<br>resources = [&quot;*&quot;]<br>}<br>}</pre><p>The goal is to attach one of these IAM Policies to “neo”, based on the value of a new input variable called give_neo_cloudwatch_full_access:</p><pre>variable &quot;give_neo_cloudwatch_full_access&quot; {<br>description = &quot;If true, neo gets full access to CloudWatch&quot;<br>type = bool<br>}</pre><p>To perform if-else condition in Terraform, you can use the count parameter and a conditional expression on each of the resources:</p><pre>resource &quot;aws_iam_user_policy_attachment&quot; &quot;neo_cloudwatch_full_access&quot; {<br>count = var.give_neo_cloudwatch_full_access ? 1 : 0<br>user = aws_iam_user.example[0].name<br>policy_arn = aws_iam_policy.cloudwatch_full_access.arn<br>}<br>resource &quot;aws_iam_user_policy_attachment&quot; &quot;neo_cloudwatch_read_only&quot; {<br>count = var.give_neo_cloudwatch_full_access ? 0 : 1<br>user = aws_iam_user.example[0].name<br>policy_arn = aws_iam_policy.cloudwatch_read_only.arn<br>}</pre><p>If the variable give_neo_cloudwatch_full_access is set to true, the &quot;CloudWatch Full Access&quot; policy is attached, as indicated by count = 1 in the first resource, while the second resource (read-only policy) is skipped with count = 0. Conversely, if the variable is false, the read-only policy is attached, and the full-access policy is skipped. Both resources reference the same IAM user, ensuring that only one of the policies is applied at a time, depending on the condition. This approach makes the code more efficient by dynamically attaching the appropriate policy based on the defined variable.</p><h3>3. Conditional Iteration with for_each and for Expressions</h3><p>Terraform’s for_each and for expressions let you iterate over collections like lists, maps, or sets and create resources based on conditions within those collections.</p><h4>Example Use Case: Dynamic Security Group Rules</h4><p>Let’s say you want to apply different security group rules based on a set of conditions. Here’s how you can use for_each with conditionals:</p><pre>variable &quot;environments&quot; {<br>  default = [&quot;dev&quot;, &quot;prod&quot;]<br>}<br>resource &quot;aws_security_group&quot; &quot;example&quot; {<br>  name = &quot;example&quot;<br>  dynamic &quot;ingress&quot; {<br>    for_each = var.environments == &quot;prod&quot; ? [ { from_port = 80, to_port = 80, protocol = &quot;tcp&quot;, cidr_blocks = [&quot;0.0.0.0/0&quot;] } ] : []<br>    content {<br>      from_port   = ingress.value.from_port<br>      to_port     = ingress.value.to_port<br>      protocol    = ingress.value.protocol<br>      cidr_blocks = ingress.value.cidr_blocks<br>    }<br>  }<br>}</pre><p>In this example:</p><ul><li>If the environment is &quot;prod&quot;, a specific ingress rule will be created for port 80.</li><li>If it’s any other environment, no ingress rule is added.</li></ul><p>This dynamic block uses the for_each loop and conditionally creates network rules, making the infrastructure flexible for different environments.</p><h4>4.Conditionals with the if String Directive</h4><p>The syntax -for directive: %{ for &lt;ITEM&gt; in &lt;COLLECTION&gt; }&lt;BODY&gt;%{ endfor }</p><p>The syntax-if directive: %{ if &lt;CONDITION&gt; }&lt;TRUEVAL&gt;%{ endif }</p><p>where CONDITION is any expression that evaluates to a boolean and TRUEVAL is the expression to render if CONDITION evaluates to true.</p><pre>variable &quot;names&quot; {<br>description = &quot;Names to render&quot;<br>type = list(string)<br>default = [&quot;neo&quot;, &quot;trinity&quot;, &quot;morpheus&quot;]<br>}<br>output &quot;for_directive_index_if_strip&quot; {<br>value = &lt;&lt;EOF<br>%{~ for i, name in var.names ~}<br>${name}%{ if i &lt; length(var.names) - 1 }, %{ endif }<br>%{~ endfor ~}<br>EOF<br>}</pre><p>you can use strip markers (~) in your string directives, which remove any extra whitespace before or after the marker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*5IsLNhow2eS4JD9cYTIqfA.png" /></figure><p>You can make this output even prettier by adding an else to the string directive, which uses the following syntax:</p><p>%{ if &lt;CONDITION&gt; }&lt;TRUEVAL&gt;%{ else }&lt;FALSEVAL&gt;%{ endif }</p><p>where FALSEVAL is the expression to render if CONDITION evaluates to false. Here’s an example of how to use the else clause to add a period at the end:</p><pre>output &quot;for_directive_index_if_else_strip&quot; {<br>value = &lt;&lt;EOF<br>%{~ for i, name in var.names ~}<br>${name}%{ if i &lt; length(var.names) - 1 }, %{ else }.%{ endif }<br>%{~ endfor ~}<br>EOF<br>}</pre><h3>Best Practices for Using Conditionals in Terraform</h3><ol><li><strong>Keep It Simple</strong>: While conditionals are powerful, avoid over-complicating your Terraform configurations. Too many nested conditionals can make your code hard to read and maintain.</li><li><strong>Use Variables Wisely</strong>: Leverage variables to manage conditionals across multiple resources. This keeps your code DRY (Don’t Repeat Yourself) and easier to scale.</li><li><strong>Use Terraform Modules</strong>: If you find yourself repeating similar conditionals, consider packaging them into a module. Modules help encapsulate logic and make your code more reusable and organized.</li><li><strong>Test Thoroughly</strong>: Since conditionals dynamically change resource behaviour, always test your configurations in different environments (e.g., dev, staging, prod) to ensure everything works as expected.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7444595b64fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Loops Simplify Infrastructure as Code with Terraform]]></title>
            <link>https://medium.com/@Rajiya.Shaik/how-loops-simplify-infrastructure-as-code-with-terraform-b1baa0afa198?source=rss-10e98ddb953e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1baa0afa198</guid>
            <dc:creator><![CDATA[Rajiya Shaik]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 10:12:05 GMT</pubDate>
            <atom:updated>2024-09-10T10:12:05.060Z</atom:updated>
            <content:encoded><![CDATA[<h4>Loops in Terraform</h4><p>Loops allow you to create multiple resources in Terraform without having to manually copy and paste blocks of code. By using loops, you can dynamically scale resources like virtual machines, storage buckets, or security groups, depending on the requirements of your infrastructure.</p><p>Terraform offers several different looping constructs.</p><ul><li><strong>count parameter</strong>: to loop over resources and modules</li><li><strong>for_each expressions:</strong> to loop over resources, inline blocks within a resource, and modules</li><li><strong>for expressions: </strong>to loop over lists and maps</li><li><strong>for string directive:</strong> to loop over lists and maps within a string</li></ul><ol><li><strong>Loops with the count Parameter:</strong></li></ol><p>Terraform resource has a meta-parameter you can use called count. Consider the following Terraform code, which should live in live/global/iam/main.tf:</p><pre>provider &quot;aws&quot; {<br>region = &quot;us-east-2&quot;<br>}<br>resource &quot;aws_iam_user&quot; &quot;example&quot; {<br>count = 3<br>name = &quot;neo.${count.index}&quot;<br>}</pre><p>when you run terraform init and terraform plan you will see that Terraform wants to create three IAM users, each with a different name (“neo.0”, “neo.1”, “neo.2”)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*7KAOY8Xsll1O8kqXhMcpFA.png" /></figure><p>Terraform supports <strong><em>Array lookup syntax</em></strong>-The syntax for looking up members of an array in Terraform is similar to most other programming languages: <strong><em>ARRAY[&lt;INDEX&gt;] </em></strong>For example, here’s how you would look up the element at index 1 of <strong><em>var.user_names[1]</em></strong>.</p><pre>name = var.user_names[count.index]</pre><p><strong><em>The length function-</em></strong>Terraform has a built-in function called<strong><em> length</em></strong> that has the syntax: <strong>length(&lt;ARRAY&gt;). </strong>The length function returns the number of items in the given ARRAY var.user_names.</p><pre>count = length(var.user_names)</pre><pre>variable &quot;user_names&quot; {<br>description = &quot;Create IAM users with these names&quot;<br>type = list(string)<br>default = [&quot;wafiq&quot;, &quot;naira&quot;, &quot;razia&quot;]<br>}<br>resource &quot;aws_iam_user&quot; &quot;example&quot; {<br>count = length(var.user_names)<br>name = var.user_names[count.index]<br>}<br>output &quot;all_arns&quot; {<br>value = aws_iam_user.example[*].arn<br>description = &quot;The ARNs for all users&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*EqwJZ0dWHmVTabJP4NKGfQ.png" /></figure><p>When you run the <strong>apply</strong> command, the <em>all_arns</em> output will contain the list of all ARNs.</p><p>Here is the Terrafrom code to deploy the 3 instances in 3 availability zones of us-east-2 region.</p><pre>terraform {<br>  required_version = &quot;&gt;= 1.0.0, &lt; 2.0.0&quot;<br><br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;aws&quot; {<br>  region = &quot;us-east-2&quot;<br>}<br><br>resource &quot;aws_instance&quot; &quot;example_1&quot; {<br>  count         = 3<br>  ami           = &quot;ami-0fb653ca2d3203ac1&quot;<br>  instance_type = &quot;t2.micro&quot;<br>}<br><br>resource &quot;aws_instance&quot; &quot;example_2&quot; {<br>  count             = length(data.aws_availability_zones.all.names)<br>  availability_zone = data.aws_availability_zones.all.names[count.index]<br>  ami               = &quot;ami-0fb653ca2d3203ac1&quot;<br>  instance_type     = &quot;t2.micro&quot;<br>}<br><br>data &quot;aws_availability_zones&quot; &quot;all&quot; {}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lha6pKuVMWX2Kw0i7u6k0g.png" /></figure><p>Limitations of countparameter:</p><ol><li>You can use to loop over an entire resource, you can’t use count<br>within a resource to loop over inline blocks.</li><li>When using count in Terraform, removing an item from the middle of an array causes all subsequent items to shift, leading Terraform to delete and recreate resources, which can cause disruptions and data loss.</li></ol><pre>variable &quot;user_names&quot; {<br>description = &quot;Create IAM users with these names&quot;<br>type = list(string)<br>default = [&quot;wafiq&quot;, &quot;razia&quot;]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMBsG_Jskt9evkVF4BO1VQ.png" /><figcaption>Here instead of deleting naira user, naira is renamed as razia and razia user is destroyed.</figcaption></figure><p><strong>2.Loops with for_each Expressions:</strong></p><p>The for_each expression enables looping over lists, sets, and maps to create multiple copies of an entire resource, multiple copies of an inline block within a resource, multiple copies of a module.</p><p><strong><em>multiple copies of an entire resource:</em></strong></p><p>Here’s how to create the same three IAM users using for_each on a resource:</p><pre>resource &quot;aws_iam_user&quot; &quot;example&quot; {<br>  for_each = toset(var.user_names)<br>  name     = each.value<br>}</pre><p>In this example, toset converts the var.user_names list into a set, as for_each supports only sets and maps for resources. The loop assigns each username to each.value, and while each.key is also available, it is generally used with key-value maps.</p><p><strong>3.Loops with for Expressions:</strong></p><p>If you need a loop to set a single variable Terraform offers functionality in the form of a forexpression.The basic syntax of a for expression is as follows:</p><p>[for &lt;ITEM&gt; in &lt;LIST&gt; : &lt;OUTPUT&gt;]</p><p>where LIST is a list to loop over, ITEM is the local variable name to assign to each item in LIST, and OUTPUT is an expression that transforms ITEM in some way. For example, here is the Terraform code to convert the list of names in var.names to uppercase:</p><pre>output &quot;upper_names&quot; {<br>value = [for name in var.names : upper(name)]<br>}</pre><p>You can filter the resulting list by specifying a condition:</p><pre>output &quot;short_upper_names&quot; {<br>value = [for name in var.names : upper(name) if length(name) &lt; 5]<br>}</pre><p>Terraform’s for expression also allows you to loop over a map using the following syntax:</p><p>[for &lt;KEY&gt;, &lt;VALUE&gt; in &lt;MAP&gt; : &lt;OUTPUT&gt;]</p><p>Here, MAP is a map to loop over, KEY and VALUE are the local variable names to assign to each key-value pair in MAP, and OUTPUT is an expression that transforms KEY and VALUE in some way. Here’s an example:</p><pre>variable &quot;hero_thousand_faces&quot; {<br>description = &quot;map&quot;<br>type = map(string)<br>default = {<br>neo = &quot;hero&quot;<br>trinity = &quot;love interest&quot;<br>morpheus = &quot;mentor&quot;<br>}<br>}<br>output &quot;bios&quot; {<br>value = [for name, role in var.hero_thousand_faces : &quot;${name} is the ${role}&quot;]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1q88W0_Vjq3_AQmFVJsbA.png" /></figure><p>You can also use for expressions to output a map rather than a list.</p><pre>output &quot;upper_roles&quot; {<br>value = {for name, role in var.hero_thousand_faces : upper(name) =&gt; upper(role)}<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9QKrTGs9MDHU-xKWFPrZ3w.png" /></figure><p><strong>4.Loops with the for String Directive:</strong></p><p>String interpolations allow you to reference Terraform code within strings: &quot;helllo, ${var.name}</p><p>String directives allow you to use control statements (e.g., for-loops and if-statements) within strings using a syntax similar to string interpolations, but instead of a dollar sign and curly braces (${…}), you use a percent sign and curly braces (%{…}).</p><p>Terraform supports two types of string directives: for-loops and conditionals. The for string directive uses the following syntax:</p><p>%{ for &lt;ITEM&gt; in &lt;COLLECTION&gt; }&lt;BODY&gt;%{ endfor }</p><p>where COLLECTION is a list or map to loop over, ITEM is the local variable name to assign to each item in COLLECTION, and BODY is what to render each iteration (which can reference ITEM). Here’s an example:</p><pre>variable &quot;names&quot; {<br>description = &quot;Names to render&quot;<br>type = list(string)<br>default = [&quot;neo&quot;, &quot;trinity&quot;, &quot;morpheus&quot;]<br>}<br>output &quot;for_directive&quot; {<br>value = &quot;%{ for name in var.names }${name}, %{ endfor }&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*dhqMyj8LHqB_T8eoiZV78Q.png" /></figure><p>There’s also a version of the for string directive syntax that gives you the index in the for-loop:</p><pre>output &quot;for_directive_index&quot; {<br>value = &quot;%{ for i, name in var.names }(${i}) ${name}, %{ endfor }&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*9qOo95agB5a4lTHvOa_npA.png" /></figure><p>Terraform’s loops and conditionals greatly simplify Infrastructure as Code by making configurations more modular, reusable, and dynamic. They allow you to manage complex infrastructure efficiently, reducing code duplication and improving maintainability.</p><p>In the next blog we will discuss about how conditionals help in simplifying the infrastructure.</p><p>Reference:</p><p>Terraform Up &amp; Running-Writing Infrastructure as Code by-</p><p>- Yevgeniy Brikman</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1baa0afa198" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Reusable Infrastructure with Terraform Modules]]></title>
            <link>https://medium.com/@Rajiya.Shaik/building-reusable-infrastructure-with-terraform-modules-2e8893b45ad4?source=rss-10e98ddb953e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e8893b45ad4</guid>
            <dc:creator><![CDATA[Rajiya Shaik]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 18:37:57 GMT</pubDate>
            <atom:updated>2024-09-07T18:37:57.821Z</atom:updated>
            <content:encoded><![CDATA[<p>Infrastructure as Code (IaC) has revolutionized how organizations manage their infrastructure, making it more scalable, consistent, and reliable. One of the most popular IaC tools is <strong>Terraform</strong>, known for its flexibility in managing multi-cloud environments. But as your infrastructure grows in complexity, maintaining modularity and reusability becomes key to avoiding duplication, reducing errors, and streamlining infrastructure changes.</p><p>This is where <strong>Terraform modules</strong> come in. Modules enable you to build reusable, modular, and maintainable infrastructure. In this blog, we’ll explore why and how you should build reusable infrastructure with Terraform modules.</p><h3>Why Use Terraform Modules?</h3><p>Terraform modules help structure your configuration into reusable, manageable components. Here are the top reasons to use them:</p><h3>1. Reusability</h3><p>Modules allow you to write code once and reuse it across different environments (dev, staging, production) or projects, saving time and reducing duplication.</p><h3>2. Simplified Management</h3><p>By abstracting complex infrastructure setups into simple modules, you can reduce the cognitive load of managing and understanding infrastructure code.</p><h3>3. Consistency</h3><p>Modules help enforce consistency in your infrastructure. When you use the same module across environments, you ensure that your resources are provisioned uniformly, reducing configuration drift.</p><h3>4. Versioning and Testing</h3><p>Modules can be versioned, which allows you to track changes and roll back if necessary. This also simplifies testing because you can focus on testing the module itself, not every individual resource in the module.</p><h3>Core Concepts of Terraform Modules</h3><p>Before we dive into creating reusable modules, let’s cover some core concepts:</p><ul><li><strong>Module:</strong> A module is a container for multiple resources that are used together. Every Terraform configuration file can be treated as a module. Even if you do not explicitly define a module, the root directory of your configuration is considered a module.</li><li><strong>Inputs and Outputs:</strong> Inputs allow you to parameterize the module, making it more flexible. Outputs enable you to export values from your module for use elsewhere.</li><li><strong>State Management:</strong> When using modules, state management becomes crucial, as the state file holds the current infrastructure status. Terraform automatically manages this but consider using remote backends like S3 or Terraform Cloud for multi-user environments.</li></ul><h3>Creating Reusable Terraform Modules</h3><p>Let’s walk through the process of building a reusable module using Terraform.</p><h3>Step 1: Define the Infrastructure</h3><p>Let’s assume you are managing a simple AWS EC2 instance. In a typical setup, you might define an EC2 resource like this:</p><pre>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}<br>resource &quot;aws_instance&quot; &quot;web&quot; {<br>  ami           = &quot;ami-0c55b159cbfafe1f0&quot;<br>  instance_type = &quot;t2.micro&quot;<br>}</pre><p>While this works, it’s not reusable. Instead, you can turn this into a module that accepts parameters, making it flexible for different environments or use cases.</p><h3>Step 2: Structure Your Module</h3><p>The directory structure for a Terraform module typically looks like this:</p><pre>/modules/<br>  └── ec2/<br>      ├── main.tf<br>      ├── variables.tf<br>      └── outputs.tf</pre><ul><li><strong>main.tf</strong>: Defines the actual resources.</li><li><strong>variables.tf</strong>: Contains the input variables to parameterize the module.</li><li><strong>outputs.tf</strong>: Declares the outputs that the module will return.</li></ul><h3>Step 3: Build the EC2 Module</h3><h4>Main.tf</h4><p>In main.tf, define your EC2 instance like so:</p><pre>resource &quot;aws_instance&quot; &quot;this&quot; {<br>  ami           = var.ami<br>  instance_type = var.instance_type<br>  tags = {<br>    Name = var.instance_name<br>  }<br>}</pre><h4>Variables.tf</h4><p>In variables.tf, define the variables that will make this module.</p><pre>variable &quot;ami&quot; {<br>  description = &quot;The AMI to use for the instance&quot;<br>  type        = string<br>}<br>variable &quot;instance_type&quot; {<br>  description = &quot;The type of instance to create&quot;<br>  type        = string<br>  default     = &quot;t2.micro&quot;<br>}<br>variable &quot;instance_name&quot; {<br>  description = &quot;Name of the EC2 instance&quot;<br>  type        = string<br>}</pre><p>This makes your module flexible, allowing you to provide different AMIs, instance types, and names for different environments.</p><h4>Outputs.tf</h4><p>In outputs.tf, declare any outputs you might want to access from outside the module.</p><pre>output &quot;instance_id&quot; {<br>  description = &quot;The ID of the EC2 instance&quot;<br>  value       = aws_instance.this.id<br>}<br>output &quot;public_ip&quot; {<br>  description = &quot;The public IP of the EC2 instance&quot;<br>  value       = aws_instance.this.public_ip<br>}</pre><p>These outputs will allow users of the module to retrieve important information like the instance ID and public IP address.</p><h3>Step 4: Use the Module in Your Root Configuration</h3><p>Now that you’ve created a reusable module, let’s see how you can use it in your infrastructure configuration.</p><pre>provider &quot;aws&quot; {<br>  region = &quot;us-east-1&quot;<br>}<br>module &quot;ec2_instance&quot; {<br>  source        = &quot;./modules/ec2&quot;<br>  ami           = &quot;ami-0c55b159cbfafe1f0&quot;<br>  instance_type = &quot;t2.micro&quot;<br>  instance_name = &quot;MyEC2Instance&quot;<br>}<br>output &quot;instance_id&quot; {<br>  value = module.ec2_instance.instance_id<br>}<br>output &quot;public_ip&quot; {<br>  value = module.ec2_instance.public_ip<br>}</pre><p>In this example, we reference the ec2 module by its relative path and pass in the required variables. The source parameter can also point to a remote module repository, such as a public or private GitHub repo or a Terraform Registry module.</p><h3>Step 5: Testing and Versioning Your Module</h3><p>Once your module is ready and tested in one environment, you can version it using Git or other version control systems. Store the module in a centralized repository for team members to access and reuse. You can tag versions so that different teams can use specific versions of the module, ensuring stability.</p><h3>Best Practices for Terraform Modules</h3><p>To get the most out of Terraform modules, follow these best practices:</p><h3>1. Keep Modules Simple</h3><p>Each module should do one thing well. Avoid large, monolithic modules that manage all parts of your infrastructure. Instead, create smaller, purpose-specific modules like ec2_instance, vpc, security_group, etc.</p><h3>2. Use Input Validation</h3><p>Use variable types and validation in variables.tf to ensure that your modules are used correctly. For example, specify that an input must be a string, or require a list for a multi-AZ setup.</p><h3>3. Document Your Modules</h3><p>Clearly document the purpose, inputs, and outputs of your modules. Add descriptions to variables and use markdown files (README.md) to explain how to use the module. Well-documented modules are easier to understand and use by your team.</p><h3>4. Version Control Your Modules</h3><p>Always store your modules in a version-controlled repository like Git. Use tags for specific releases, allowing teams to lock modules to a stable version or update them when needed.</p><h3>5. Test Modules in Isolation</h3><p>Before using a module in production, test it in isolation using a sandbox environment. You can use tools like <strong>Terratest</strong> to automate testing of your modules.</p><h3>Conclusion</h3><p>Terraform modules are a powerful way to create reusable, modular, and maintainable infrastructure as code. By abstracting complex infrastructure configurations into small, reusable components, modules enable consistency, simplify management, and reduce duplication. When used correctly, they allow your infrastructure to scale effortlessly while remaining organized and maintainable.</p><p>With the guidelines outlined in this blog, you’re now ready to start building reusable Terraform modules and taking your infrastructure management to the next level. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e8893b45ad4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>