<?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 Nithin john on Medium]]></title>
        <description><![CDATA[Stories by Nithin john on Medium]]></description>
        <link>https://medium.com/@nithinjohn97?source=rss-90aa86726a96------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YKX56_Dxntp1g7SW</url>
            <title>Stories by Nithin john on Medium</title>
            <link>https://medium.com/@nithinjohn97?source=rss-90aa86726a96------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:49:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nithinjohn97/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[Apache Log Parser With Python]]></title>
            <link>https://medium.com/@nithinjohn97/apache-log-parser-with-python-5007a91a04ce?source=rss-90aa86726a96------2</link>
            <guid isPermaLink="false">https://medium.com/p/5007a91a04ce</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Nithin john]]></dc:creator>
            <pubDate>Fri, 05 May 2023 14:01:38 GMT</pubDate>
            <atom:updated>2023-05-05T14:08:17.299Z</atom:updated>
            <content:encoded><![CDATA[<p>As part of this DevOps project, we showcase how Python scripting can be used to parse Apache access logs in real-world scenarios. Two years ago, I posted a shell script (<a href="https://github.com/NITHIN-JOHN-GEORGE/apache_log_parser">https://github.com/NITHIN-JOHN-GEORGE/apache_log_parser</a>) for performing this operation. The following is a Python implementation of the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*2Wy1MK-8k_tHq_86TKtRUw.png" /></figure><h3>Concepts in Python used in this Project:</h3><ul><li>Regex with re module</li><li>Arg parser Module</li><li>Functions</li><li>OS module</li><li>sys module</li><li>csv and datetime module</li><li>Counter from Collection Module</li><li>Loops</li><li>Conditional Statements</li></ul><h3>About The Project</h3><p>The script allows users to analyze and extract specific data from Apache access log files. The Apache access log file is a text file that contains information about requests made to the Apache webserver. This information includes details such as the IP address of the client making the request, the request method used, the time and date of the request, the requested URL, and the HTTP status code returned by the server.</p><p>The script accepts user input parameters, including the location of the Apache access log file to parse, the type of operation to perform, and the output format of the result (either table or CSV). It uses the argparse module to parse user input parameters.</p><p>The script is designed to accept three user input parameters:</p><ul><li>the location of the Apache access log file to parse</li><li>the type of operation to perform.</li><li>and the output format of the result (either table or CSV)</li></ul><p>The script can perform four types of operations.</p><ul><li>First, it can count the most frequently visited IP addresses, returning the IP addresses with the highest number of hits. The script uses regular expressions to extract IP addresses from the log file and the Counter module to count the number of occurrences of each IP address.</li><li>Second, it can count the number of times each request method (GET, POST, PUT, or DELETE) appears in the log file and returns the methods with the highest number of hits.</li><li>Third, it can count the number of times each base URL (the part of the URL before the query string) appears in the log file and returns the URLs with the highest number of hits. The script uses regular expressions to extract base URLs from the log file and the Counter module to count the number of occurrences of each base URL.</li><li>Finally, it can count the number of times each HTTP status code appears in the log file and returns the codes with the highest number of hits.</li></ul><p>The script uses regular expressions to extract the relevant data from the log file and the Counter module to count the number of occurrences of each data point. It also includes helper functions for checking if the log file exists and for printing headers and centering text .The script uses the os and datetime modules to generate timestamps and get the size of the terminal window.</p><p>Once the script has performed the requested operation, it outputs the results either to the console or a CSV file, depending on the user’s specified output format. If the output format is “table,” the script formats the output as a table using the print function. If the output format is “CSV,” the script writes the output to a CSV file using the csv module.</p><p>Project Repository : <a href="https://github.com/NITHIN-JOHN-GEORGE/apache-log-parser-python">https://github.com/NITHIN-JOHN-GEORGE/apache-log-parser-python</a></p><p>A sample dataset for Apache access.log can be found here ( only for demo) :</p><p>Running the script:</p><pre>- git clone &lt;https://github.com/NITHIN-JOHN-GEORGE/apache-log-parser-python.git&gt;</pre><pre>- cd Apache-log-parser-python</pre><pre>- python3 apache-log-parser.py -h</pre><p><strong>Running the Help of the script:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBFWidDKyOwlu132FYGZHQ.png" /></figure><p><strong>Running the script without any argument:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AIOyFSvjL21oTHRw4y0ncw.png" /></figure><h3><strong>Count the most frequently visited IP addresses:</strong></h3><pre><strong>python3 apache-log-parser.py -l access.log -o most-visited-ips -f table<br></strong><br># Note : To generate a csv report you can use<br><br><strong>python3 apache-log-parser.py -l access.log -o most-visited-ips -f csv<br></strong><br># It will generate csv file with current timestamp of file creation<br><br># Example: most_visited_ip_2023-04-24-23-41-38.csv</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaqwhcrXX3Hq6lc7lkJ2fw.png" /></figure><h3><strong>Counting the number of times each request method in the log file:</strong></h3><pre><strong>python3 apache-log-parser.py -l access.log -o top-request-methods -f table<br></strong><br># Note : To generate a csv report you can use<br><br><strong>python3 apache-log-parser.py -l access.log -o most-visited-ips -f csv<br></strong><br># It will generate csv file with current timestamp of file creation<br><br># Example: top_request_methods_2023-04-24-23-48-05.csv</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5w_W6X0swHr4ZficVdx5RA.png" /></figure><h3>Counting the number of times each base URL appears in the log file</h3><pre><strong>python3 apache-log-parser.py -l access.log -o top-base-urls -f table<br></strong><br># Note : To generate a csv report you can use<br><br><strong>python3 apache-log-parser.py -l access.log -o top-base-urls -f csv<br></strong><br># It will generate csv file with current timestamp of file creation<br><br># Example: top_base_urls_2023-04-24-23-52-52.csv</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArZLX2LpHVc1pYParJSwFg.png" /></figure><h3>Counting the number of times each HTTP status code appears in the log file</h3><pre><strong>python3 apache-log-parser.py -l access.log -o top-http-status-codes -f table<br></strong><br># Note : To generate a csv report you can use<br><br><strong>python3 apache-log-parser.py -l access.log -o top-http-status-codes -f csv<br></strong><br># It will generate csv file with current timestamp of file creation<br><br># Example: top_base_urls_2023-04-24-23-52-52.csv</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTsp_SQ6ePScJp4Oy_T7eQ.png" /></figure><p>Thats all ! Thank you for reading my article , have a nice day and keep learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5007a91a04ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What happens internally when we type ls -l command in the shell ?]]></title>
            <link>https://medium.com/@nithinjohn97/what-happens-internally-when-we-type-ls-l-command-in-the-shell-a3b51a1cb96d?source=rss-90aa86726a96------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3b51a1cb96d</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Nithin john]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 19:23:45 GMT</pubDate>
            <atom:updated>2023-04-09T19:23:45.916Z</atom:updated>
            <content:encoded><![CDATA[<h3>What happens internally when we type ls -l command in the shell ? How It Works and What You Need to Know?</h3><p>The Shell acts as an interface between the user and the kernel in an operating system. It allows users to interact with the system by providing a command-line or graphical user interface (GUI) through which they can execute commands or run applications. When a user enters a command, the Shell interprets it and communicates with the kernel to carry out the requested operation.</p><p>And , a command is instruction that the user gives to the Shell to perform a specific task.</p><h3>System call</h3><p>A system call is a request made by a process running in user space to the operating system kernel to perform an operating system service on behalf of the process. When a program running in user space needs to perform an operating system service, it makes a system call by invoking a specific function provided by the operating system.</p><p>Simply put , System calls are calls to the Kernel code to do <em>something.</em></p><h3>How does ls -l command works internally?</h3><p>When you enter a command, the first thing the shell does is it breaks the entire command into “tokens.” The shell will then look for a program name belonging to the first token in the command line.</p><p>In this example, ‘ls -l’ is composed of two tokens, ‘ls’, and ‘-l.’ Next it checks for shell expansion i.e.,</p><p>The shell first verifies whether the first token entered by the user is an alias. If an alias exists, it replaces it with the corresponding actual command. Additionally, the shell expands any other aliases defined by the user before proceeding.</p><p>If there is no alias present , the shell first checks if the entered command is a built-in command or not. Then , it looks for the location of the executable program file, such as “ls,” in the system’s directories specified in the $PATH environment variable. The $PATH variable is a list of directories that the shell searches through whenever a command is entered.</p><p>After identifying the $PATH variable, the shell breaks down all the directories in the $PATH using ‘:’ as a delimiter(tokenizing it) . If the shell fails to find the executable file in any of the directories listed in the $PATH variable, or if the command is neither a shell function nor an alias, the shell will throw an error.</p><p>If the command is located successfully, the shell examines the remaining tokens to identify if they are variables, shell parameters, or arguments to the command. In case they are variables or parameters, the shell will perform an expansion of these elements, replacing them with their original values in the command.</p><blockquote><em>In Linux , most of the executable files are located in </em><strong><em>‘/usr/bin’ .</em></strong><em> The binary executable file of ls also will be there ( </em><strong><em>‘/usr/bin/ls’ )</em></strong></blockquote><p>After finding the “ls” executable file, the shell creates a new process, which is an instance of a program that needs to be executed. To execute the “ls” command, the shell uses three system calls: fork, , and wait. The shell duplicates itself (making a copy of itself) using the fork() system call, creating a child process that is a copy of the parent process (the shell).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2RQpHiHlOJ500vn_Z7r2Q.png" /></figure><p>After creating the child process with the fork system call, the child process runs the <strong>execve</strong> system call ( execution system call ) with the path to the “ls” executable and its arguments.</p><p>Then the system program will use some system calls to load all the libraries required by the program into the virtual memory at run-time ( dynamic loading )</p><p>We can use <strong>strace</strong> command to trace all system calls happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*62WgTMjmvqAIFbje6WQsYw.png" /></figure><p>While the child process executes it, the parent process waits for execution to be completed and once the execution call ends, the child process will indicate that it has finished and returns the response to the parent process through another system call called <em>wait()</em> and then the child process is terminated with the exit() system .</p><p>Once this execution process has been carried out, the memory used in these processes is freed, the response or result of the command will be displayed on the user’s screen, and the parent process takes over again and waits for the next input from the user.</p><blockquote><em>In a program where you use fork, you also have to use wait() system call. wait() system call is used to wait in the parent process for the child process to finish.</em></blockquote><p>Thank you for reading my article , have a nice day and keep learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3b51a1cb96d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Cloud Infrastructure with Terraform Cloud: A Deep Dive into its Capabilities]]></title>
            <link>https://medium.com/techbeatly/automating-cloud-infrastructure-with-terraform-cloud-a-deep-dive-into-its-capabilities-9bc9d0aff929?source=rss-90aa86726a96------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bc9d0aff929</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Nithin john]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 20:43:35 GMT</pubDate>
            <atom:updated>2023-03-27T04:47:30.471Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will discover how Terraform Cloud can help you streamline your cloud infrastructure management process and we will explore the powerful features that make it a must-have tool for cloud infrastructure management.</p><p>We will deliver the reasons why Terraform Cloud is essential, highlighting its capabilities and benefits, advanced workflows, and much more. We’ll take a closer look at the VCS-driven workflow, providing a detailed example to illustrate how it works in practice.</p><p>Plus, we’ll provide some practical recommendations for using Terraform Cloud in a production environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxC0r1H3Ebtx4DNnARfqRA.png" /></figure><p>One of the main benefits of using Terraform to manage cloud infrastructure is that it allows for infrastructure automation. With Terraform, developers and operations teams can define and manage their infrastructure in code, rather than manually configure resources through a web console or command line interface. This makes it easier to manage large, complex environments and reduces the risk of human error.</p><p>Earlier, when using Terraform, the typical workflow involved developers defining their infrastructure as code using the Terraform configuration language(HCL), and then using the <strong>terraform plan</strong> and <strong>terraform apply</strong> commands to provision the infrastructure on their local machines.</p><p>The state of the infrastructure, which tracks the current state of the resources managed by Terraform, was often stored locally as well. However, as our cloud infrastructure grew, we started seeing inconsistencies and issues in the terraform state file as many team members were deploying resources at the same time.</p><p>That’s where Terraform cloud came in as a savior.</p><p>Terraform cloud is a managed solution offered by <a href="https://www.hashicorp.com/">Hashicorp</a> to run Terraform configurations.</p><blockquote>Terraform Cloud is available as a hosted service at <a href="https://app.terraform.io/"><strong>https://app.terraform.io</strong></a>.</blockquote><p>It acts as a CI/CD tool for deploying Infrastructure as Code (IaC)</p><p>It offers a central UI for all your project and <strong>provides remote state management</strong> also it manages <strong>Terraform runs ( plan / apply ) in a consistent and reliable environment</strong>, <strong>access controls for approving changes to infrastructure</strong>, <strong>a private registry for sharing Terraform modules</strong>, <strong>Cost Estimation</strong>, <strong>Drift Detection</strong>, <strong>Sentinel for Governance</strong> (policy controls for governing the contents of Terraform configurations), and more.</p><p>You can use it to manage cloud infrastructure, including Amazon Web Services, Google Cloud Platform, and Microsoft Azure. It’s a recommended product if you needed to manage resources within an enterprise and you have a whole team contributing to it.</p><h3>Why use Terraform Cloud?</h3><ol><li><strong>Remote execution:</strong></li></ol><p>It allows you to run Terraform plan and apply operations on infrastructure hosted in the cloud (TFC) or on a central system that you can control (Terraform Cloud Enterprise)</p><p><strong>2. Terraform cloud workspaces</strong>:</p><p><strong>Workspaces</strong> are simply referring to <strong>environments.</strong> It works like separate working directories.</p><p>If we use multiple environments like <strong>development, QA,</strong> and <strong>production,</strong> we need to manage independent codes for each and every environment.</p><p>But with the help of Workspaces, we can use a single code for multiple environments and manage the <strong>State files</strong> of all the environments independently. It helps to create multiple State files with the same Terraform configurations.</p><p>Terraform cloud manages infrastructure collections with workspaces. It works like separate working directories. Cloud workspaces are not limited to state files, configurations, variables, state management &amp; credentials &amp; secrets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6twSStM0F4Ki4ESHuJZilA.png" /></figure><p>In addition to the basic Terraform content, Terraform Cloud keeps some additional data for each workspace:</p><ul><li><strong>State versions:</strong> Each workspace retains backups of its previous state files. Although only the current state is necessary for managing resources, the state history can be useful for tracking changes over time or recovering from problems.</li><li><strong>Run History:</strong> When Terraform Cloud manages a workspace’s Terraform runs, it retains a record of all run activity, including summaries, logs, a reference to the changes that caused the run, and user comments.</li></ul><p><strong>3. Version control integration and triggers:</strong></p><p>As Terraform Cloud is an infrastructure-as-code service, It supports Version control system integration with some of VCS providers like GitHub, Gitlab, Azure DevOps, and Bitbucket. <strong>Terraform executions can be triggered upon new commits merged by pull requests or pushed in VCS. It can work as a CICD pipeline.</strong></p><p><strong>4. Private registry:</strong></p><p>Reusable modules are very useful when needing to provision multiple environments from the same source configuration when the requirement is to store that module privately in a Terraform cloud. The private registry can be used in this scenario. A private<strong> registry allows us to store modules and use those modules in workspaces.</strong></p><p><strong>5. Access Control &amp; Governance:</strong></p><p>Large teams in organizations have many workspaces in Terraform cloud, And to manage access to those workspaces across team members is required most, <strong>Terraform cloud provides paid functionality to meet the control and governance needs of large organizations</strong>.</p><p><strong>6. Sentinel policies &amp; Cost estimation:</strong></p><p>Terraform cloud provides sentinel, which is a policy-as-code framework. Which is used to <strong>enforce granular policies about how the infrastructure should get provisioned</strong>. Examples like limiting the size of virtual machines, confining major updates to defined maintenance windows, etc. These policies can act as firm requirements, advisory warnings, or soft requirements, which can be bypassed through explicit approval from the team.</p><p><strong>7. Drift Detection:</strong></p><p>It <strong>continuously checks against the infrastructure state to detect changes and provide alerts</strong>. This allows Terraform to provide a central pane of visibility to all your infrastructure and offers operators confidence that it matches the last known Terraform state.</p><p><strong>8. Cost Optimization:</strong></p><p>Cost Optimization is a unique feature of Terraform cloud. <strong>Before making changes to the provider, Terraform cloud can display an estimate of its total cost, as well as any change in cost caused by proposed updates</strong>.</p><p>Cost optimization can also be integrated with sentinel policies for warnings. It ensures that all your infrastructure is governed and has the proper security measures in place. It also reduces the potential for application downtime that could negatively impact the user experience and, eventually, revenue.</p><h3>How does it work?</h3><p>Terraform Cloud uses organizations and workspaces to organize your code and environments.</p><p><strong>“Organizations are shared spaces for teams to collaborate on infrastructure”.</strong></p><p>Each organization can have multiple workspaces that define groups of resources of your infrastructure.</p><p>Normally, a user will create one organization (common use case for small and medium companies) and have multiple workspaces describing your environments</p><p><strong>Organizing Workspaces with Projects</strong></p><p>A project is a container that holds multiple workspaces. Projects help to organize workspaces and one key benefit of using projects is that they allow for more granular control over permissions. Each project has separate permission set that you can use to grant teams access to all workspaces in the project.</p><p>Every workspace must belong to exactly one project. By default, all workspaces belong to an organization’s <strong>Default Project</strong>.</p><h3>Enough of theory, Let’s start with the Practicals:</h3><h4>First, we will create the Organization itself:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0n0snnI82OCIxFCSTghtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkQsi0z_35daHpHSUFZ7bQ.png" /></figure><h4>Next, We will be Connecting to a version control provider</h4><p>Connecting Terraform Cloud to your VCS involves four steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*pI49KP3_chvzMYPJldGgoQ.png" /></figure><ol><li>Go to your organization’s settings and then click Providers. The VCS Providers page appears.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwZCA-DG9YWTRHJqLOURIA.png" /></figure><p>2. Click <strong>Add VCS Provider</strong>. The <strong>VCS Providers</strong> page appears.</p><p>3. Select <strong>GitHub</strong> and then select <a href="http://github.com/"><strong>GitHub.com</strong></a> from the menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKEwITg9CbudKDz345lA-Q.png" /></figure><p>This will take us to the page where have to configure OAuth authentication with your VCS provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KjmwZosy5dF2aA8LXNSVtw.png" /></figure><p>Next thing on Github, we have to create <strong>a New OAuth Application</strong> This page is located at <a href="https://github.com/settings/applications/new">https://github.com/settings/applications/new</a>.</p><p>You can also reach it through GitHub’s menus:</p><ul><li>Click your profile picture and choose “Settings.”</li><li>Click “Developer settings,” then make sure you’re on the “OAuth Apps” page (not “GitHub Apps”).</li><li>Click the “New OAuth App” button.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QwRWXAHw5y42uZfQAGMDw.png" /></figure><p>Fill it with the details you got above from the setup provider section and click on register application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeTuh-5SQDV9OLt19Bg1cg.png" /></figure><p>Next click on generate a new client secret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7tJeDRt_zGJB7ix0REghw.png" /></figure><p>Now go back to the Terraform Cloud, Enter the Client ID and Client Secret from the previous step, as well as an optional Name for this VCS connection. Click “Connect and continue.” This takes you to a page on GitHub.com, asking whether you want to authorize the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bL3vQvIltHy4SKnv-feIbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7bYiQlLFiSsFjN5_jZ_kg.png" /></figure><p>Click the green “Authorize &lt;GITHUB USER&gt;&quot; button at the bottom of the authorization page. GitHub might request your password to confirm the operation.</p><p>Next, if the organization repositories include Git submodules that can only be accessed via SSH, an SSH key can be added along with the OAuth credentials. <strong>We will be skipping this step</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmUrFr6uzqSHNmQ4efwZgw.png" /></figure><p>And that’s it, we have created a new VCS provider to connect to GitHub</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syRIY-e1AI17cwIRr1iLiw.png" /></figure><h3>Terraform Cloud Workflows</h3><p>Terraform Cloud has three workflows for managing Terraform runs.</p><ul><li><strong>The </strong><a href="https://developer.hashicorp.com/terraform/cloud-docs/run/ui"><strong>UI/VCS-driven run workflow</strong></a><strong> </strong>— here you are connecting your VCS to Terraform Cloud — easily integrate version control such as GitHub, GitLab, BitBucket or Azure DevOps and automatically initiate Terraform runs when changes are committed to the specified branch</li><li><strong>The API-driven run workflow </strong>— you can use your standard Terraform CLI to trigger remote runs.</li><li><strong>The </strong><a href="https://developer.hashicorp.com/terraform/cloud-docs/run/cli"><strong>CLI-driven run workflow</strong></a><strong> </strong>— where you can manage and trigger runs through other tools by triggering calls to Terraform Cloud.</li></ul><blockquote>Here in this blog, we will be more focusing on the VCS-driven workflow.</blockquote><h4>VCS Driven Workflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rHqJLh8c-34o1T2zLrxszA.png" /></figure><p>Some of the features:</p><ul><li>initiating speculative plans every time a PR is created against the default branch (this is set up by default so you don’t have to do anything)</li><li>once PR is merged this will trigger the plan and apply, however by default applying will require manual approval.</li><li>you have various triggers to choose from. I will discuss this more when coming to an example.</li></ul><blockquote><em>Sample repo containing some terraform code for testing can be found under: </em><a href="https://github.com/NITHIN-JOHN-GEORGE/terraform-cloud-demo">https://github.com/NITHIN-JOHN-GEORGE/terraform-cloud-demo</a></blockquote><h3>Creating a Workspace</h3><p>Click <strong>Projects &amp; workspaces →</strong> Click <strong>New</strong>, then select <strong>Workspace →</strong> Choose a workflow type: <strong>Version control →</strong> Choose a <strong>repository</strong></p><p>Enter a <strong>Workspace Name →</strong> choose a <strong>Project</strong> to add the workspace to → Open Advanced options to configure <strong>Terraform Working Directory, Set up AutoRun Triggering, and setting up the VCS branch.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wYQgLLSzDVENzy79dY1fQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCIy_Z-XBeYXxr6EGBXlBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dJUKf_0zYw70EE1n02V5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tObAzAnO_YvnTi0txRov9A.png" /></figure><p><strong>Note :</strong></p><p>Terraform Cloud provides different types of triggers to start a run automatically based on specific events. These triggers can be customized to suit the needs of your workflow.</p><p>The first type of trigger is the path changes trigger, which is particularly useful for monorepos where multiple projects are stored in a single repository. With this trigger, you can configure Terraform Cloud to start a run whenever a change occurs in a specific directory or file path within the repository. This means you don’t have to run the entire codebase and can focus on the relevant changes.</p><p>The second and recommended type of trigger is a pattern-based trigger. This trigger uses glob patterns to select which changes should trigger a run and ignore others. For example, if you only require a run when there is a change in .tf files in the “tfe-test” directory, you can specify the pattern as “/tfe-test/*.tf”. This ensures that Terraform Cloud only runs when specific changes occur, reducing the risk of unintended consequences and speeding up the deployment process.</p><p><strong>This is an important configuration to be noted, otherwise, the workspace will be triggered every time a code changes in any other sub-directory in the Github-Repo.</strong></p><p>Next Click on Create Workspace</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Y-mR2702t-sTOtEV5xQDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbAeguNcx0QXdCEhb01--w.png" /></figure><p>Here we can directly configure variables, or we can skip and do it afterward.</p><p>Next, Go to Workspace Overview → Click on Configure Variables</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4CuLi1Uo8m0MQkgfb9SJA.png" /></figure><p>Here you can add new variables which are required !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRdA0TB_ojxTKvKKXuE-Cw.png" /></figure><p>Here note we are adding a new variable called AWS_ACCESS_KEY. This is a variable that must be kept confidential so we have to click on <strong>Sensitive.</strong></p><p>Here we can also directly declare variables as Environment variables .</p><p>Repeat the same for all variables you have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1_InxuMdjEj30B53pGC-A.png" /></figure><p>As you can see the sensitive variables cannot be seen from the console, we also cannot see if we edit it, we can only update the value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*meyhvF6p4B6UVA5In4M_KQ.png" /></figure><p>That’s it.</p><p>Now go to Actions → Start a new run</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2Nau0B3N8ZKf8wOnT97Pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8XqUKgP6wWZ01tJoD1-IA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttmDbO8qzeCAAp8hM1QNCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TuyrAdK3iXWqwj2dkjc78w.png" /></figure><p>It will wait for our Confirmation for Applying. Click on Confirm &amp; Apply</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6mVF1HGW50LIpsOCZIncw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzTU07vShE02TdHsG9CXWQ.png" /></figure><p>We can see the states got saved here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0snJS77So1puz5Ij7bTrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyNQRwZIw2svVCpJEaDV4g.png" /></figure><p>And we can see a list of all Runs that happened:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DgoLfoscgEC6FhVLDj1mNA.png" /></figure><p><strong>Now, let&#39;s test the Auto triggering Functionality !!</strong></p><p>Let&#39;s modify some parts of code and as soon as you push the code to GitHub, the Terraform runs will be triggered</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjbzuD0qXhCKXj5xjHslrQ.png" /></figure><p>And that&#39;s it, it got triggered !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmIlOvnrv253Tn2NcTgpjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBFIVaDuQS9YROpo_t4kpw.png" /></figure><p>This confirms Everything Working Fine as Expected !!</p><p>There are other features of TF cloud like private module registry, configuring TF-agents, sentinel policies, drift detection,cost-estimation, etc .. we will be covering some of them in the upcoming blogs.</p><blockquote><strong>Configuring TF agents in our environment where can have complete control of the infrastructure, sentinel policies, drift detection, and cost estimation is paid feature and comes under the Business Plan of Terraform cloud</strong></blockquote><h4><strong>Recommendations while using TF cloud in production :</strong></h4><ol><li>Add notifications for all events / certain events to a slack channel for workspaces with the prod prefix</li><li>Use self-hosted TF-agents</li><li>Use TF cloud for hosting our private modules</li><li>Alternatively, write a backup script that automatically sends the state to s3 and does cross-region replication for disaster-recovery purposes and create workspaces with the states from S3.</li><li>Provide granular access to terraform workspaces across team members with access controls.</li><li>Set the Terraform log level to <em>debug</em></li><li>Use Features like Drift Detection ( which continuously checks against the infrastructure state to detect and notify when there are changes), Cost Estimation, and Sentinel Policies ( granular policies about how the infrastructure should get provisioned ).</li></ol><p>Thanks for Reading !! Happy Learning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bc9d0aff929" width="1" height="1" alt=""><hr><p><a href="https://medium.com/techbeatly/automating-cloud-infrastructure-with-terraform-cloud-a-deep-dive-into-its-capabilities-9bc9d0aff929">Automating Cloud Infrastructure with Terraform Cloud: A Deep Dive into its Capabilities</a> was originally published in <a href="https://medium.com/techbeatly">techbeatly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximizing Cost-Efficiency  with Karpenter : Setting Up EKS Cluster (v1.24)]]></title>
            <link>https://medium.com/techbeatly/maximizing-cost-efficiency-with-karpenter-setting-up-eks-cluster-v1-24-b68bbd64f23c?source=rss-90aa86726a96------2</link>
            <guid isPermaLink="false">https://medium.com/p/b68bbd64f23c</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Nithin john]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 19:10:09 GMT</pubDate>
            <atom:updated>2023-03-27T04:47:49.879Z</atom:updated>
            <content:encoded><![CDATA[<h3>Maximizing Cost-Efficiency with Karpenter : Setting Up EKS Cluster (v1.24) on Spot-Instances with AWS ALB Ingress Controller, Amazon EBS CSI Driver, and Add-ons Completely using Terraform and Terraform Cloud</h3><p>In this blog you will learn how to provision EKS Kubernetes cluster at any scale using <a href="https://github.com/awslabs/karpenter">Karpenter</a> . We will also utilize <strong>spot instances</strong> to reduce costs by up to 90 percent. Additionally, we’ll set up the <strong>AWS ALB Ingress Controller</strong> and <strong>Amazon EBS CSI driver</strong>, establish trust between an OIDC-compatible identity provider and your AWS account using <strong>IAM OIDC identity provider</strong> (including the necessary IAM roles and policies), install the metrics server, and set up required EKS add-ons using Terraform. We will deploy all of this using Helm charts and configure custom values.yml using Terraform as well. Finally, we will use Terraform Cloud for remote state, creating workspaces, and the plan/apply workflow.</p><blockquote>If you would like to skip the theoretical explanations please fell free scroll down to the actual <strong>terraform configurations</strong> and where do the testings!!</blockquote><h3>Kuberenetes Autoscaling</h3><p>A Kubernetes Cluster is a group of node machines that run containerized applications. Inside these nodes, Pods run containers that demand resources such as CPU, memory, and sometimes disk or GPU.</p><p>Getting the size of a Kubernetes cluster right is not an easy task, if the number of nodes provisioned is too high, resources might be underutilized and if it’s too low, new workloads won’t be able to be scheduled in the cluster.</p><p>Setting the number of nodes manually is a simple approach, but it requires manual intervention every time the cluster needs to grow or to shrink, and it will make nearly impossible to adapt the cluster size to cover rapid traffic and load fluctuations.</p><p>One of the benefits of using Kubernetes is its ability to <strong>dynamically scale your infrastructure based on user demand</strong>.</p><p>Kubernetes offers multiple layers of auto-scaling functionality, including:</p><p><strong>Pod-based autoscaling</strong></p><ul><li><a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">Horizontal Pod Autoscaler</a> — adds or removes more pods to the deployment as needed</li><li><a href="https://cloud.google.com/kubernetes-engine/docs/concepts/verticalpodautoscaler">Vertical Pod Autoscaler</a> — resizes pod’s CPU and memory requests and limits to match the load</li></ul><p><strong>Node-based autoscaling</strong>: adding or removing nodes as needed</p><ul><li><a href="https://github.com/kubernetes/autoscaler/tree/master/cluster-autoscaler">Cluster Autoscaler</a></li><li><a href="https://karpenter.sh/docs/getting-started/">Karpenter</a></li></ul><h3>How we can reduce cost with Using Spot Instances?</h3><p>AWS offers a cost-saving option for EC2 instances called “Spot instances” where AWS provides the unused/unoccupied EC2 instances for up to a <strong>90% cheaper</strong> than regular On-Demand instances. However, their availability is not guaranteed as they are unused instances that are made available to users.</p><p>When a Spot instance is reallocated, AWS automatically provides a new instance to take its place. While Spot instances are similar to regular On-Demand instances, they come with a risk of potential interruption, but they can be an effective way to save costs for workloads that are not time-sensitive.</p><p>Spot instances are compatible with Amazon Elastic Kubernetes Service (EKS), and they can be used to scale production applications when there is a surge in demand. By leveraging Spot instances, users can take advantage of cost savings while also ensuring that their applications can handle spikes in traffic without compromising performance.</p><p>One downside of using Spot Instances is that they can be interrupted by the AWS EC2 Spot service, which is why it’s crucial to design your application with fault-tolerance in mind. To help with this, you can utilize Spot Instance interruption notices, which provide a two-minute warning before Amazon EC2 stops or terminates your instance. Keep in mind that after this notification, the instance will be reclaimed. By designing your application to handle interruptions gracefully, you can minimize the impact of Spot Instance interruptions and still benefit from the cost savings they offer.</p><h3>Why use Karpenter instead of Cluster Autoscaler?</h3><p>Cluster Autoscaler is a useful Kubernetes tool that can adjust the size of a Kubernetes cluster by adding or removing nodes, based on the utilization metrics of nodes and the presence of pending pods. However, it requires nodes with the same capacity to function correctly.</p><p>To adjust the capacity, Kubernetes Cluster Autoscaler interacts with the Autoscaling group service directly. To properly work , AWS EKS managed node groups are needed, and the Autoscaler only scales up or down the managed node groups through Amazon EC2 Auto Scaling Groups. Whenever a new node group is added, it is essential to inform Cluster Autoscaler about it, as there is a mapping between Cluster Autoscaler, which is Kubernetes native, and the node group, which is AWS native.</p><p>Cluster Autoscaler does not provide flexibility to handle hundreds of instance types, zones, and purchase options.</p><p>Unlike Autoscaler, <strong>Karpenter doesn’t rely on node groups ,it manages each instance directly</strong>. Instead, autoscaling configurations are specified in <strong>provisioners</strong>, which can be seen as a more customizable alternative to EKS-managed node groups.</p><ul><li>If you are uncertain about the instance types you require or have no specific requirements, Karpenter can make the decision for you. All you need to do is create a provisioner that outlines the minimum parameter requirements.</li><li>Karpenter is designed to make efficient use of the full range of instance types available through AWS. Unlike other autoscaling tools that may be limited in the instance types they can use, Karpenter can select and utilize any instance type that meets the needs of incoming pods.</li><li>Karpenter looks at the workload (i.e pods) and launches the right instances for the situation.</li><li>Karpenter manages instances directly, without the need for additional orchestration mechanisms such as node groups. This allows it to retry capacity requests in a matter of milliseconds, significantly reducing the time it takes to address capacity issues.Moreover, Karpenter’s direct management approach enables it to make <strong>efficient use of diverse instance types, availability zones, and purchase options, without the need to create numerous node groups</strong>. This results in a more flexible and cost-effective solution for managing Kubernetes clusters on AWS.</li><li>Infrastructure <strong>costs are reduced</strong> by looking for under-utilized nodes and removing them, also by replacing expensive nodes with cheaper alternatives, and by consolidating workloads onto more efficient compute resources.</li><li>Karpenter operates on an intent-based model when making instance selection decisions. This model takes into account the specific resource requests and scheduling requirements of incoming pods. By doing so, Karpenter can identify the most suitable instance type to handle these pods, which may involve requesting a larger instance type capable of accommodating all the pods on a single node.</li></ul><p>For instance, if there are 50 pending pods waiting to be scheduled, Karpenter will calculate the resource requirements of these pods and select an appropriate instance type to accommodate them. Unlike Cluster Autoscaler, which may need to scale several nodes to meet the demand, Karpenter can request a single large EC2 instance and place all the pods on it.</p><h3>How it works?</h3><p>Karpenter is designed to observe events within the Kubernetes cluster and send commands to the underlying cloud provider’s compute service. Upon installation, Karpenter begins to monitor the specifications of unschedulable Pods and calculates the aggregate resource requests. Based on this information, it can make decisions to launch and terminate nodes in order to reduce scheduling latencies and infrastructure costs.</p><p>To achieve this, Karpenter leverages a Custom Resource Definition (CRD) called Provisioner. The Provisioner specifies the node provisioning configuration, including the instance size/type, topology (such as availability zone), architecture (e.g. arm64, amd64), and lifecycle type (such as spot, on-demand, preemptible).</p><p>Karpenter is designed to automatically manage the lifecycle of nodes provisioned by Kubernetes. When a node is no longer needed or has exceeded its TTL (time-to-live), Karpenter triggers a finalization process that includes several steps to gracefully decommission the node.</p><p>One event that can trigger finalization is the expiration of a node’s configuration, as defined by the <strong>ttlSecondsUntilExpired</strong> parameter. This parameter specifies the maximum amount of time that a node can remain active before being terminated. When the node&#39;s TTL expires, Karpenter takes action by cordoning off the node, which means that no new workloads can be scheduled on it. Karpenter then begins to drain the pods running on the node, which involves moving the workloads to other nodes in the cluster. Finally, Karpenter terminates the underlying compute resource associated with the node and deletes the node object.</p><p>Another event that can trigger finalization is when the last workload running on a Karpenter provisioned node is terminated. In this case, Karpenter follows the same process of cordoning the node, draining the pods, terminating the underlying resource, and deleting the node object.</p><p>By automating the finalization process, Karpenter ensures that nodes are only active when they are needed, which can help to optimize the performance and cost-effectiveness of Kubernetes clusters on AWS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cqn8bflEDs-vbiAl2RIy7Q.png" /></figure><h3>How Karpenter handles Spot Interruptions</h3><p>Karpenter requires a queue to exist that receives event messages from EC2 and health services in order to handle interruption messages properly for nodes</p><p>Karpenter will keep watching for upcoming involuntary interruption events that would cause disruption to your workloads.</p><p>These events include <strong>Spot Interruption Warnings, Scheduled Change Health Events, Instance Terminating Events, and Instance Stopping Events</strong>.</p><p>When Karpenter detects that one of these events is imminent, it automatically performs cordoning, draining, and termination of the affected node(s) to allow enough time for cleanup of workloads prior to compute disruption. This is particularly useful in scenarios where the terminationGracePeriod for workloads is long or where cleanup is critical, as it ensures that there is enough time to gracefully clean up pods.</p><p><strong>Karpenter achieves this by monitoring an SQS queue</strong> that receives critical events from AWS services that could potentially affect nodes. However, <strong>to use this feature, it is necessary to provision an SQS queue and add EventBridge rules and targets that forward interruption events from AWS services to the SQS queue.</strong></p><h3>Now lets get into action !!!</h3><p>I am assuming that the <strong>underlying VPC and network resources are already created.</strong></p><blockquote>I will be creating a seperate blog on setting up Production Grade VPC (HA) with environment-specific run method which we used <strong>.</strong></blockquote><p>The public subnets in the VPC must be tagged with :</p><pre>&quot;kubernetes.io/cluster/&lt;cluster-name&gt;&quot; = &quot;owned&quot;<br>&quot;karpenter.sh/discovery&quot; = &lt;cluster-name&gt; <br>&quot;kubernetes.io/role/elb&quot; = 1</pre><p>The private subnets in the VPC must be tagged with :</p><pre>&quot;kubernetes.io/cluster/&lt;cluster-name&gt;&quot; = &quot;owned&quot;<br>&quot;karpenter.sh/discovery&quot; = &lt;cluster-name&gt; <br>&quot;kubernetes.io/role/internal-elb&quot; = 1</pre><p>Also we will be adding the following tags to the security group of control plane and eks-nodes:</p><pre>&quot;karpenter.sh/discovery&quot; = &lt;cluster-name&gt;</pre><p>We will be discussing this when we move ahead!!!</p><h3>Creating the EC2 spot Linked Role</h3><p>This step is only necessary if this is the first time you’re using EC2 Spot in this account. It is necessary to exist in your account in order to let you launch Spot instances.</p><pre>aws iam create-service-linked-role --aws-service-name spot.amazonaws.com</pre><h3>Configuring the EKS Cluster !!</h3><p>Next we will be deploying the cluster itself first , which has deployed a minimum set of On-Demand instances that we will use to deploy Kubernetes controllers on it.</p><p>After that we will use Karpenter to deploy Spot instances to showcase a few of the benefits of running a group-less auto scaler.</p><p>Terraform code for Setting up the entire stack can be found at :</p><p><a href="https://github.com/NITHIN-JOHN-GEORGE/eks-karpenter-controllers-spot-terraform">https://github.com/NITHIN-JOHN-GEORGE/eks-karpenter-controllers-spot-terraform</a></p><h3>Creating Terraform files For the Setup !!</h3><p><strong>Provider Configuration</strong></p><pre>terraform {<br>  required_version = &quot;~&gt; 1.0&quot;<br>  <br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 4.16.0&quot;<br>    }</pre><pre>    kubernetes = {<br>      source = &quot;hashicorp/kubernetes&quot;<br>      version = &quot;~&gt; 2.18.0&quot;<br>    }</pre><pre>    kubectl = {<br>      source  = &quot;gavinbunney/kubectl&quot;<br>      version = &quot;&gt;= 1.7.0&quot;<br>    }</pre><pre>    helm = {<br>      source = &quot;hashicorp/helm&quot;<br>      version = &quot;2.8.0&quot;<br>    }<br>  }<br>}<br>provider &quot;aws&quot; {<br>  region  = var.region<br>  access_key = var.AWS_ACCESS_KEY<br>  secret_key = var.AWS_SECRET_KEY</pre><pre>}</pre><pre>output &quot;endpoint&quot; {<br>  value = data.aws_eks_cluster.cluster.endpoint<br>}</pre><pre># output &quot;kubeconfig-certificate-authority-data&quot; {<br>#   value = base64decode(data.aws_eks_cluster.cluster.certificate_authority.0.data)<br># }</pre><pre>provider &quot;kubernetes&quot; {<br>  host                   = data.aws_eks_cluster.cluster.endpoint<br>  cluster_ca_certificate = base64decode(data.aws_eks_cluster.cluster.certificate_authority.0.data)<br>  token                  = data.aws_eks_cluster_auth.cluster.token<br>}</pre><pre>provider &quot;kubectl&quot; {<br>  host                   = data.aws_eks_cluster.cluster.endpoint<br>  cluster_ca_certificate = base64decode(data.aws_eks_cluster.cluster.certificate_authority.0.data)<br>  token                  = data.aws_eks_cluster_auth.cluster.token<br>  load_config_file       = false<br>}</pre><pre>provider &quot;helm&quot; {<br>  kubernetes {<br>    host                   = data.aws_eks_cluster.cluster.endpoint<br>     token                  = data.aws_eks_cluster_auth.cluster.token<br>     cluster_ca_certificate = base64decode(data.aws_eks_cluster.cluster.certificate_authority.0.data)<br>  }<br>}</pre><p><strong>EKS Cluster Setup</strong></p><pre>locals {<br>  env = [&quot;prod&quot;, &quot;qa&quot;, &quot;dev&quot;]<br>}<br><br>#------------Security group for eks-cluster--------------------------------------------------<br>resource &quot;aws_security_group&quot; &quot;control_plane_sg&quot; {<br>  count                = contains(local.env, var.env) ? 1 : 0<br>  name   = &quot;k8s-control-plane-sg&quot;<br>  vpc_id = &quot;${data.aws_vpc.vpc.id}&quot;<br>  tags = {<br>    Name = &quot;k8s-control-plane-sg&quot;<br>    vpc_id = &quot;${data.aws_vpc.vpc.id}&quot;<br>    ManagedBy = &quot;terraform&quot;<br>    Env       = var.env<br>    &quot;karpenter.sh/discovery&quot; = var.cluster_name<br>  }<br>}<br>#----------------------Security group traffic rules for eks cluster------------------------------------------<br>## Ingress rule<br>resource &quot;aws_security_group_rule&quot; &quot;control_plane_inbound&quot; {<br>  description   = &quot;Allow worker Kubelets and pods to receive communication from the cluster control plane&quot;  <br>  security_group_id = element(aws_security_group.control_plane_sg.*.id,0)<br>  type              = &quot;ingress&quot;<br>  from_port   = 0<br>  to_port     = 65535<br>  protocol    = &quot;tcp&quot;<br>  cidr_blocks = flatten([&quot;${values(data.aws_subnet.public_subnets).*.cidr_block}&quot;, &quot;${values(data.aws_subnet.private_subnets).*.cidr_block}&quot;])<br>}<br>## Egress rule<br>resource &quot;aws_security_group_rule&quot; &quot;control_plane_outbound&quot; {<br>  security_group_id = element(aws_security_group.control_plane_sg.*.id,0)<br>  type              = &quot;egress&quot;<br>  from_port   = 0<br>  to_port     = 65535<br>  protocol    = &quot;-1&quot;<br>  cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>}<br>#------------Security group for eks-nodes--------------------------------------------------<br>resource &quot;aws_security_group&quot; &quot;eks-nodes&quot; {<br>  count                = contains(local.env, var.env) ? 1 : 0<br>  name        = &quot;nodes_eks_sg&quot;<br>  description = &quot;nodes_eks_sg&quot;<br>  vpc_id      = &quot;${data.aws_vpc.vpc.id}&quot;<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  tags = {<br>    Name = &quot;nodes_eks_sg&quot;<br>    vpc_id = &quot;${data.aws_vpc.vpc.id}&quot;<br>    ManagedBy = &quot;terraform&quot;<br>    Env       = var.env<br>    &quot;karpenter.sh/discovery&quot; = var.cluster_name<br>  }<br>}<br>#---------Security group traffic rules for node-security-group----------------<br>## Ingress rule<br>resource &quot;aws_security_group_rule&quot; &quot;nodes_ssh&quot; {<br>  security_group_id =  element(aws_security_group.eks-nodes.*.id,0)<br>  type              = &quot;ingress&quot;<br>  from_port         = 22<br>  to_port           = 22<br>  protocol          = &quot;tcp&quot;<br>  cidr_blocks       = flatten([&quot;${values(data.aws_subnet.public_subnets).*.cidr_block}&quot;, &quot;${values(data.aws_subnet.private_subnets).*.cidr_block}&quot;])<br>}<br>#--------------------cloud-watch-log-group-- for eks cluster----------------------------------------------<br>resource &quot;aws_cloudwatch_log_group&quot; &quot;eks_log_group&quot; {<br>  name              = &quot;/aws/eks/${var.cluster_name}/cluster&quot;<br>  retention_in_days = var.retention_day<br>  tags = {<br>    Name = &quot;/aws/eks/${var.cluster_name}/cluster&quot;<br>    vpc_id = &quot;${data.aws_vpc.vpc.id}&quot;<br>    ManagedBy = &quot;terraform&quot;<br>    Env       = var.env<br>  }<br>  <br>}<br>#-----------------EKS-cluster-code--------------------------------------------<br>resource &quot;aws_eks_cluster&quot; &quot;eks-cluster&quot; {<br>  count                = contains(local.env, var.env) ? 1 : 0<br>  name     = &quot;${var.cluster_name}&quot;<br>  enabled_cluster_log_types = [&quot;api&quot;,&quot;audit&quot;,&quot;authenticator&quot;,&quot;controllerManager&quot;,&quot;scheduler&quot;]<br>  version  = &quot;${var.eks_version}&quot;<br>  role_arn = element(aws_iam_role.EKSClusterRole.*.arn,0)<br>  vpc_config {<br>    endpoint_private_access = true<br>    endpoint_public_access  = true<br>    security_group_ids = [&quot;${element(aws_security_group.control_plane_sg.*.id,0)}&quot;]<br>    subnet_ids         = flatten([&quot;${values(data.aws_subnet.private_subnets).*.id}&quot;])<br>  }<br>  tags = {<br>    Name = &quot;${var.cluster_name}&quot;<br>    vpc_id = &quot;${data.aws_vpc.vpc.id}&quot;<br>    ManagedBy = &quot;terraform&quot;<br>    &quot;karpenter.sh/discovery&quot; = var.cluster_name<br>    Env       = var.env<br>  }<br>  depends_on = [<br>    aws_cloudwatch_log_group.eks_log_group,<br>    aws_iam_role_policy_attachment.eks-cluster-AmazonEKSClusterPolicy,<br>    aws_iam_role_policy_attachment.eks-cluster-AmazonEKSServicePolicy,<br>  ]<br>}<br>#--------------eks-private-node-group----------------------------------------------<br>resource &quot;aws_eks_node_group&quot; &quot;node-group-private&quot; {<br>  cluster_name    = element(aws_eks_cluster.eks-cluster.*.name,0)<br>  node_group_name = var.node_group_name<br>  node_role_arn   = element(aws_iam_role.NodeGroupRole.*.arn,0)<br>  subnet_ids      = flatten([&quot;${values(data.aws_subnet.private_subnets).*.id}&quot;])<br>  capacity_type  = &quot;ON_DEMAND&quot;<br>  ami_type       = var.ami_type<br>  disk_size      = var.disk_size<br>  instance_types = var.instance_types<br>  scaling_config {<br>    desired_size = var.node_desired_size<br>    max_size     = var.node_max_size<br>    min_size     = var.node_min_size<br>  }<br>  <br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>  timeouts {}<br>  remote_access {<br>    ec2_ssh_key = var.ec2_ssh_key_name_eks_nodes<br>    source_security_group_ids = [element(aws_security_group.eks-nodes.*.id,0)]<br>  }<br>   <br>  labels         = {<br>    &quot;eks/cluster-name&quot;   = element(aws_eks_cluster.eks-cluster.*.name,0)<br>    &quot;eks/nodegroup-name&quot; = format(&quot;nodegroup_%s&quot;, lower(element(aws_eks_cluster.eks-cluster.*.name,0)))<br>  }<br>  tags = merge({<br>    Name                 = var.node_group_name<br>    &quot;eks/cluster-name&quot;   = element(aws_eks_cluster.eks-cluster.*.name,0)<br>    &quot;eks/nodegroup-name&quot; = format(&quot;nodegroup_%s&quot;, lower(element(aws_eks_cluster.eks-cluster.*.name,0)))<br>    &quot;kubernetes.io/cluster/${var.cluster_name}&quot; = &quot;owned&quot;<br>    &quot;karpenter.sh/discovery/${var.cluster_name}&quot; = var.cluster_name<br>    &quot;karpenter.sh/discovery&quot; = var.cluster_name<br>    &quot;eks/nodegroup-type&quot; = &quot;managed&quot;<br>    vpc_id = &quot;${data.aws_vpc.vpc.id}&quot;<br>    ManagedBy = &quot;terraform&quot;<br>    Env       = var.env<br>  })<br>  # Ensure that IAM Role permissions are created before and deleted after EKS Node Group handling.<br>  # Otherwise, EKS will not be able to properly delete EC2 Instances and Elastic Network Interfaces.<br>  depends_on = [<br>    aws_eks_cluster.eks-cluster,<br>    aws_iam_role_policy_attachment.AmazonEKSWorkerNodePolicy,<br>    aws_iam_role_policy_attachment.AmazonEKS_CNI_Policy,<br>    aws_iam_role_policy_attachment.AmazonEC2ContainerRegistryReadOnly,<br>  ]<br>}<br># ADD-ONS<br>resource &quot;aws_eks_addon&quot; &quot;addons&quot; {<br>  for_each          = { for addon in var.addons : addon.name =&gt; addon }<br>  cluster_name      = element(aws_eks_cluster.eks-cluster.*.name,0)<br>  addon_name        = each.value.name<br>  resolve_conflicts = &quot;OVERWRITE&quot;<br>  depends_on = [aws_eks_cluster.eks-cluster , aws_eks_node_group.node-group-private ]<br>}<br><br></pre><p><strong>IAM roles and Policies for EKS cluster and NodeGroup</strong></p><pre># IAM role for EKS cluster <br><br>resource &quot;aws_iam_role&quot; &quot;EKSClusterRole&quot; {<br>  count                = contains(local.env, var.env) ? 1 : 0<br>  name = &quot;EKSClusterRole_v2&quot;<br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Action = &quot;sts:AssumeRole&quot;<br>        Effect = &quot;Allow&quot;<br>        Principal = {<br>          Service = &quot;eks.amazonaws.com&quot;<br>        }<br>      },<br>    ]<br>  })<br>}<br># Adding policies to the IAM role for EKS cluster<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;eks-cluster-AmazonEKSClusterPolicy&quot; {<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEKSClusterPolicy&quot;<br>  role       = element(aws_iam_role.EKSClusterRole.*.name,0)<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;eks-cluster-AmazonEKSVPCResourceController&quot; {<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEKSVPCResourceController&quot;<br>  role       = element(aws_iam_role.EKSClusterRole.*.name,0)<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;eks-cluster-AmazonEKSServicePolicy&quot; {<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonEKSServicePolicy&quot;<br>  role       = element(aws_iam_role.EKSClusterRole.*.name,0)<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;eks_CloudWatchFullAccess&quot; {<br>  policy_arn = &quot;arn:aws:iam::aws:policy/CloudWatchFullAccess&quot;<br>  role       =element(aws_iam_role.EKSClusterRole.*.name,0)<br>}<br>## IAM role for Node group<br>resource &quot;aws_iam_role&quot; &quot;NodeGroupRole&quot; {<br>  count                = contains(local.env, var.env) ? 1 : 0<br>  name = &quot;EKSNodeGroupRole_v2&quot;<br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Action = &quot;sts:AssumeRole&quot;<br>        Effect = &quot;Allow&quot;<br>        Principal = {<br>          Service = &quot;ec2.amazonaws.com&quot;<br>        }<br>      },<br>    ]<br>  })<br>}<br>#---policy-attachements-for-Node group-role--------<br>resource &quot;aws_iam_role_policy&quot; &quot;node-group-ClusterAutoscalerPolicy&quot; {<br>  name = &quot;eks-cluster-auto-scaler&quot;<br>  role = element(aws_iam_role.NodeGroupRole.*.id,0)<br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Action = [<br>            &quot;autoscaling:DescribeAutoScalingGroups&quot;,<br>            &quot;autoscaling:DescribeAutoScalingInstances&quot;,<br>            &quot;autoscaling:DescribeLaunchConfigurations&quot;,<br>            &quot;autoscaling:DescribeTags&quot;,<br>            &quot;autoscaling:SetDesiredCapacity&quot;,<br>            &quot;autoscaling:TerminateInstanceInAutoScalingGroup&quot;<br>        ]<br>        Effect   = &quot;Allow&quot;<br>        Resource = &quot;*&quot;<br>      },<br>    ]<br>  })<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;node_group_AWSLoadBalancerControllerPolicy&quot; {<br>  policy_arn = element(aws_iam_policy.load-balancer-policy.*.arn,0)<br>  role       = element(aws_iam_role.NodeGroupRole.*.name,0)<br>}<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       = element(aws_iam_role.NodeGroupRole.*.name,0)<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       = element(aws_iam_role.NodeGroupRole.*.name,0)<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       = element(aws_iam_role.NodeGroupRole.*.name,0)<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;CloudWatchAgentServerPolicy&quot; {<br>  policy_arn = &quot;arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy&quot;<br>  role       = element(aws_iam_role.NodeGroupRole.*.name,0)<br>}<br>## SSMManagedInstanceCore Policy for Nodes (Karpenter)<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;eks_node_attach_AmazonSSMManagedInstanceCore&quot; {<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore&quot;<br>  role       = element(aws_iam_role.NodeGroupRole.*.name,0)<br>}<br># Create IAM OIDC identity providers to establish trust between an OIDC-compatible IdP and your AWS account.<br>data &quot;tls_certificate&quot; &quot;cert&quot; {<br>  url = aws_eks_cluster.eks-cluster[0].identity[0].oidc[0].issuer<br>}<br>resource &quot;aws_iam_openid_connect_provider&quot; &quot;cluster&quot; {<br>  client_id_list  = [&quot;sts.amazonaws.com&quot;]<br>  thumbprint_list = [data.tls_certificate.cert.certificates[0].sha1_fingerprint]<br>  url             = aws_eks_cluster.eks-cluster[0].identity[0].oidc[0].issuer<br>}</pre><pre><strong>IAM role and policies for ALB ingress controller</strong></pre><pre># IAM policy  for ALB ingress controller<br><br>resource &quot;aws_iam_policy&quot; &quot;load-balancer-policy&quot; {<br>  count                = contains(local.env, var.env) ? 1 : 0<br>  name        = &quot;AWSLoadBalancerControllerIAMPolicy_v2&quot;<br>  path        = &quot;/&quot;<br>  description = &quot;AWS LoadBalancer Controller IAM Policy&quot;<br>  policy = &lt;&lt;EOF<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>        {<br>          &quot;Effect&quot;: &quot;Allow&quot;,<br>          &quot;Action&quot;: [<br>                &quot;iam:CreateServiceLinkedRole&quot;<br>            ],<br>           &quot;Resource&quot;: &quot;*&quot;,<br>           &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;iam:AWSServiceName&quot;: &quot;elasticloadbalancing.amazonaws.com&quot;<br>                }<br>            }<br>         },<br>         {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ec2:DescribeAccountAttributes&quot;,<br>                &quot;ec2:DescribeAddresses&quot;,<br>                &quot;ec2:DescribeAvailabilityZones&quot;,<br>                &quot;ec2:DescribeInternetGateways&quot;,<br>                &quot;ec2:DescribeVpcs&quot;,<br>                &quot;ec2:DescribeVpcPeeringConnections&quot;,<br>                &quot;ec2:DescribeSubnets&quot;,<br>                &quot;ec2:DescribeSecurityGroups&quot;,<br>                &quot;ec2:DescribeInstances&quot;,<br>                &quot;ec2:DescribeNetworkInterfaces&quot;,<br>                &quot;ec2:DescribeTags&quot;,<br>                &quot;ec2:GetCoipPoolUsage&quot;,<br>                &quot;ec2:DescribeCoipPools&quot;,<br>                &quot;elasticloadbalancing:DescribeLoadBalancers&quot;,<br>                &quot;elasticloadbalancing:DescribeLoadBalancerAttributes&quot;,<br>                &quot;elasticloadbalancing:DescribeListeners&quot;,<br>                &quot;elasticloadbalancing:DescribeListenerCertificates&quot;,<br>                &quot;elasticloadbalancing:DescribeSSLPolicies&quot;,<br>                &quot;elasticloadbalancing:DescribeRules&quot;,<br>                &quot;elasticloadbalancing:DescribeTargetGroups&quot;,<br>                &quot;elasticloadbalancing:DescribeTargetGroupAttributes&quot;,<br>                &quot;elasticloadbalancing:DescribeTargetHealth&quot;,<br>                &quot;elasticloadbalancing:DescribeTags&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;cognito-idp:DescribeUserPoolClient&quot;,<br>                &quot;acm:ListCertificates&quot;,<br>                &quot;acm:DescribeCertificate&quot;,<br>                &quot;iam:ListServerCertificates&quot;,<br>                &quot;iam:GetServerCertificate&quot;,<br>                &quot;waf-regional:GetWebACL&quot;,<br>                &quot;waf-regional:GetWebACLForResource&quot;,<br>                &quot;waf-regional:AssociateWebACL&quot;,<br>                &quot;waf-regional:DisassociateWebACL&quot;,<br>                &quot;wafv2:GetWebACL&quot;,<br>                &quot;wafv2:GetWebACLForResource&quot;,<br>                &quot;wafv2:AssociateWebACL&quot;,<br>                &quot;wafv2:DisassociateWebACL&quot;,<br>                &quot;shield:GetSubscriptionState&quot;,<br>                &quot;shield:DescribeProtection&quot;,<br>                &quot;shield:CreateProtection&quot;,<br>                &quot;shield:DeleteProtection&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ec2:AuthorizeSecurityGroupIngress&quot;,<br>                &quot;ec2:RevokeSecurityGroupIngress&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ec2:CreateSecurityGroup&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ec2:CreateTags&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:ec2:*:*:security-group/*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;ec2:CreateAction&quot;: &quot;CreateSecurityGroup&quot;<br>                },<br>                &quot;Null&quot;: {<br>                    &quot;aws:RequestTag/elbv2.k8s.aws/cluster&quot;: &quot;false&quot;<br>                }<br>            }<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ec2:CreateTags&quot;,<br>                &quot;ec2:DeleteTags&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:ec2:*:*:security-group/*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;Null&quot;: {<br>                    &quot;aws:RequestTag/elbv2.k8s.aws/cluster&quot;: &quot;true&quot;,<br>                    &quot;aws:ResourceTag/elbv2.k8s.aws/cluster&quot;: &quot;false&quot;<br>                }<br>            }<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ec2:AuthorizeSecurityGroupIngress&quot;,<br>                &quot;ec2:RevokeSecurityGroupIngress&quot;,<br>                &quot;ec2:DeleteSecurityGroup&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;Null&quot;: {<br>                    &quot;aws:ResourceTag/elbv2.k8s.aws/cluster&quot;: &quot;false&quot;<br>                }<br>            }<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;elasticloadbalancing:CreateLoadBalancer&quot;,<br>                &quot;elasticloadbalancing:CreateTargetGroup&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;Null&quot;: {<br>                    &quot;aws:RequestTag/elbv2.k8s.aws/cluster&quot;: &quot;false&quot;<br>                }<br>            }<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;elasticloadbalancing:CreateListener&quot;,<br>                &quot;elasticloadbalancing:DeleteListener&quot;,<br>                &quot;elasticloadbalancing:CreateRule&quot;,<br>                &quot;elasticloadbalancing:DeleteRule&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;elasticloadbalancing:AddTags&quot;,<br>                &quot;elasticloadbalancing:RemoveTags&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:elasticloadbalancing:*:*:targetgroup/*/*&quot;,<br>                &quot;arn:aws:elasticloadbalancing:*:*:loadbalancer/net/*/*&quot;,<br>                &quot;arn:aws:elasticloadbalancing:*:*:loadbalancer/app/*/*&quot;<br>            ],<br>            &quot;Condition&quot;: {<br>                &quot;Null&quot;: {<br>                    &quot;aws:RequestTag/elbv2.k8s.aws/cluster&quot;: &quot;true&quot;,<br>                    &quot;aws:ResourceTag/elbv2.k8s.aws/cluster&quot;: &quot;false&quot;<br>                }<br>            }<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;elasticloadbalancing:AddTags&quot;,<br>                &quot;elasticloadbalancing:RemoveTags&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:elasticloadbalancing:*:*:listener/net/*/*/*&quot;,<br>                &quot;arn:aws:elasticloadbalancing:*:*:listener/app/*/*/*&quot;,<br>                &quot;arn:aws:elasticloadbalancing:*:*:listener-rule/net/*/*/*&quot;,<br>                &quot;arn:aws:elasticloadbalancing:*:*:listener-rule/app/*/*/*&quot;<br>            ]<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;elasticloadbalancing:ModifyLoadBalancerAttributes&quot;,<br>                &quot;elasticloadbalancing:SetIpAddressType&quot;,<br>                &quot;elasticloadbalancing:SetSecurityGroups&quot;,<br>                &quot;elasticloadbalancing:SetSubnets&quot;,<br>                &quot;elasticloadbalancing:DeleteLoadBalancer&quot;,<br>                &quot;elasticloadbalancing:ModifyTargetGroup&quot;,<br>                &quot;elasticloadbalancing:ModifyTargetGroupAttributes&quot;,<br>                &quot;elasticloadbalancing:DeleteTargetGroup&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;Null&quot;: {<br>                    &quot;aws:ResourceTag/elbv2.k8s.aws/cluster&quot;: &quot;false&quot;<br>                }<br>            }<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;elasticloadbalancing:RegisterTargets&quot;,<br>                &quot;elasticloadbalancing:DeregisterTargets&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:elasticloadbalancing:*:*:targetgroup/*/*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;elasticloadbalancing:SetWebAcl&quot;,<br>                &quot;elasticloadbalancing:ModifyListener&quot;,<br>                &quot;elasticloadbalancing:AddListenerCertificates&quot;,<br>                &quot;elasticloadbalancing:RemoveListenerCertificates&quot;,<br>                &quot;elasticloadbalancing:ModifyRule&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}<br>EOF  <br>}<br><br># IAM role and policy document for ALB ingress controller<br><br>data &quot;aws_iam_policy_document&quot; &quot;eks_oidc_assume_role&quot; {<br>  statement {<br>    actions = [&quot;sts:AssumeRoleWithWebIdentity&quot;]<br>    effect  = &quot;Allow&quot;<br>    condition {<br>      test     = &quot;StringEquals&quot;<br>      variable = &quot;${replace(data.aws_eks_cluster.cluster.identity[0].oidc[0].issuer, &quot;https://&quot;, &quot;&quot;)}:sub&quot;<br>      values = [<br>        &quot;system:serviceaccount:kube-system:aws-load-balancer-controller&quot;<br>      ]<br>    }<br>    condition {<br>      test     = &quot;StringEquals&quot;<br>      variable = &quot;${replace(data.aws_eks_cluster.cluster.identity[0].oidc[0].issuer, &quot;https://&quot;, &quot;&quot;)}:aud&quot;<br>      values = [<br>        &quot;sts.amazonaws.com&quot;<br>      ]<br>    }<br>    principals {<br>      identifiers = [<br>        &quot;arn:aws:iam::${data.aws_caller_identity.current.account_id}:oidc-provider/${replace(data.aws_eks_cluster.cluster.identity[0].oidc[0].issuer, &quot;https://&quot;, &quot;&quot;)}&quot;<br>      ]<br>      type = &quot;Federated&quot;<br>    }<br>  }<br>}<br>resource &quot;aws_iam_role&quot; &quot;alb_ingress&quot; {<br>  count                = contains(local.env, var.env) ? 1 : 0<br>  name               = &quot;${var.cluster_name}-alb-ingress&quot;<br>  assume_role_policy = data.aws_iam_policy_document.eks_oidc_assume_role.json<br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;load-balancer-policy-role&quot; {<br>  policy_arn = element(aws_iam_policy.load-balancer-policy.*.arn,0)<br>  role       = element(aws_iam_role.alb_ingress.*.name,0)<br>}</pre><p><strong>IAM roles and policies for EBS CSI driver</strong></p><pre>data &quot;aws_iam_policy_document&quot; &quot;eks_oidc_assume_role_ebs&quot; {<br>  statement {<br>    actions = [&quot;sts:AssumeRoleWithWebIdentity&quot;]<br>    effect  = &quot;Allow&quot;<br>    condition {<br>      test     = &quot;StringEquals&quot;<br>      variable = &quot;${replace(data.aws_eks_cluster.cluster.identity[0].oidc[0].issuer, &quot;https://&quot;, &quot;&quot;)}:sub&quot;<br>      values = [<br>        &quot;system:serviceaccount:kube-system:ebs-csi-controller-sa&quot;<br>      ]<br>    }<br>    principals {<br>      identifiers = [<br>        &quot;arn:aws:iam::${data.aws_caller_identity.current.account_id}:oidc-provider/${replace(data.aws_eks_cluster.cluster.identity[0].oidc[0].issuer, &quot;https://&quot;, &quot;&quot;)}&quot;<br>      ]<br>      type = &quot;Federated&quot;<br>    }<br>  }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;ebs-csi&quot; {<br>  name               = &quot;ebs-csi-role&quot;<br>  assume_role_policy = data.aws_iam_policy_document.eks_oidc_assume_role_ebs.json<br>}<br><br># IAM policy  for EBS CSI  controller<br><br>resource &quot;aws_iam_policy&quot; &quot;ebs_permissions&quot; {<br>  name        = &quot;ebs-permissions&quot;<br>  path        = &quot;/&quot;<br>  description = &quot;AWS EBS Controller IAM Policy&quot;<br>  policy = &lt;&lt;EOF<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;ec2:CreateSnapshot&quot;,<br>        &quot;ec2:AttachVolume&quot;,<br>        &quot;ec2:DetachVolume&quot;,<br>        &quot;ec2:ModifyVolume&quot;,<br>        &quot;ec2:DescribeAvailabilityZones&quot;,<br>        &quot;ec2:DescribeInstances&quot;,<br>        &quot;ec2:DescribeSnapshots&quot;,<br>        &quot;ec2:DescribeTags&quot;,<br>        &quot;ec2:DescribeVolumes&quot;,<br>        &quot;ec2:DescribeVolumesModifications&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;ec2:CreateTags&quot;<br>      ],<br>      &quot;Resource&quot;: [<br>        &quot;arn:aws:ec2:*:*:volume/*&quot;,<br>        &quot;arn:aws:ec2:*:*:snapshot/*&quot;<br>      ],<br>      &quot;Condition&quot;: {<br>        &quot;StringEquals&quot;: {<br>          &quot;ec2:CreateAction&quot;: [<br>            &quot;CreateVolume&quot;,<br>            &quot;CreateSnapshot&quot;<br>          ]<br>        }<br>      }<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;ec2:DeleteTags&quot;<br>      ],<br>      &quot;Resource&quot;: [<br>        &quot;arn:aws:ec2:*:*:volume/*&quot;,<br>        &quot;arn:aws:ec2:*:*:snapshot/*&quot;<br>      ]<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;ec2:CreateVolume&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringLike&quot;: {<br>          &quot;aws:RequestTag/ebs.csi.aws.com/cluster&quot;: &quot;true&quot;<br>        }<br>      }<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;ec2:CreateVolume&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringLike&quot;: {<br>          &quot;aws:RequestTag/CSIVolumeName&quot;: &quot;*&quot;<br>        }<br>      }<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;ec2:DeleteVolume&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringLike&quot;: {<br>          &quot;ec2:ResourceTag/CSIVolumeName&quot;: &quot;*&quot;<br>        }<br>      }<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;ec2:DeleteVolume&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringLike&quot;: {<br>          &quot;ec2:ResourceTag/ebs.csi.aws.com/cluster&quot;: &quot;true&quot;<br>        }<br>      }<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;ec2:DeleteSnapshot&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringLike&quot;: {<br>          &quot;ec2:ResourceTag/CSIVolumeSnapshotName&quot;: &quot;*&quot;<br>        }<br>      }<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;ec2:DeleteSnapshot&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;,<br>      &quot;Condition&quot;: {<br>        &quot;StringLike&quot;: {<br>          &quot;ec2:ResourceTag/ebs.csi.aws.com/cluster&quot;: &quot;true&quot;<br>        }<br>      }<br>    }<br>  ]<br>}<br>EOF  <br>}<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;ebs-csi-policy-role&quot; {<br>  policy_arn = aws_iam_policy.ebs_permissions.arn<br>  role       = aws_iam_role.ebs-csi.name<br>}</pre><p><strong>Template Files ( Custom values.yml for helm chart ) FOR ALB-INGRESS AND EBS-CSI DRIVER</strong></p><pre>data &quot;template_file&quot; &quot;alb-ingress-values&quot; {<br>  template = &lt;&lt;EOF<br>       replicaCount: 1vpcId: &quot;${data.aws_vpc.vpc.id}&quot;<br>       clusterName: &quot;${var.cluster_name}&quot;<br>       ingressClass: alb<br>       createIngressClassResource: true<br>  <br>       region: &quot;${var.region}&quot;<br>       resources:<br>          requests:<br>             memory: 256Mi<br>             cpu: 100m<br>          limits:<br>             memory: 512Mi<br>             cpu: 1000m<br>  EOF<br>}<br><br>data &quot;template_file&quot; &quot;ebs-csi-driver-values&quot; {<br>  template = &lt;&lt;EOF<br>    controller:<br>      region: &quot;${var.region}&quot;<br>      replicaCount: 1<br>      k8sTagClusterId: &quot;${var.cluster_name}&quot; <br>      updateStrategy:<br>        type: RollingUpdate<br>        rollingUpdate:<br>         maxUnavailable: 1<br>      resources:<br>        requests:<br>          cpu: 10m<br>          memory: 40Mi<br>        limits:<br>           cpu: 100m<br>           memory: 256Mi<br>      serviceAccount:<br>        create: true<br>        name: ebs-csi-controller-sa<br>        annotations: <br>            eks.amazonaws.com/role-arn: &quot;${aws_iam_role.ebs-csi.arn}&quot;<br>    storageClasses: <br>     - name: ebs-sc<br>       annotations:<br>          storageclass.kubernetes.io/is-default-class: &quot;true&quot;<br>  EOF<br>}<br></pre><h4><strong>Kuberenets Resources for ALB ingress controller</strong></h4><pre>resource &quot;kubernetes_service_account&quot; &quot;aws-load-balancer-controller-service-account&quot; {<br>  metadata {<br>    name      = &quot;aws-load-balancer-controller&quot;<br>    namespace = &quot;kube-system&quot;<br>    annotations = {<br>      &quot;eks.amazonaws.com/role-arn&quot; = data.aws_iam_role.alb_ingress.arn<br>    }<br>    labels = {<br>      &quot;app.kubernetes.io/name&quot;       = &quot;aws-load-balancer-controller&quot;<br>      &quot;app.kubernetes.io/component&quot;  = &quot;controller&quot;<br>      &quot;app.kubernetes.io/managed-by&quot; = &quot;terraform&quot;<br>    }<br>  }<br>   automount_service_account_token = true<br>  depends_on = [aws_eks_cluster.eks-cluster , aws_eks_node_group.node-group-private ]<br>}<br><br>resource &quot;kubernetes_secret&quot; &quot;aws-load-balancer-controller&quot; {<br>  metadata {<br>    name      = &quot;aws-load-balancer-controller&quot;<br>    namespace = &quot;kube-system&quot;<br>    annotations = {<br>      &quot;kubernetes.io/service-account.name&quot; = &quot;aws-load-balancer-controller&quot;<br>      &quot;kubernetes.io/service-account.namespace&quot; = &quot;kube-system&quot;<br>    }<br>  }<br>  type = &quot;kubernetes.io/service-account-token&quot;<br>  depends_on = [kubernetes_service_account.aws-load-balancer-controller-service-account , aws_eks_cluster.eks-cluster , aws_eks_node_group.node-group-private]<br>}<br><br>resource &quot;kubernetes_cluster_role&quot; &quot;aws-load-balancer-controller-cluster-role&quot; {<br>  depends_on = [aws_eks_cluster.eks-cluster , aws_eks_node_group.node-group-private ]<br>  metadata {<br>    name = &quot;aws-load-balancer-controller&quot;<br>    labels = {<br>      &quot;app.kubernetes.io/name&quot;       = &quot;aws-load-balancer-controller&quot;<br>      &quot;app.kubernetes.io/managed-by&quot; = &quot;terraform&quot;<br>    }<br>  }<br>  rule {<br>    api_groups = [<br>      &quot;&quot;,<br>      &quot;extensions&quot;,<br>    ]<br>    resources = [<br>      &quot;configmaps&quot;,<br>      &quot;endpoints&quot;,<br>      &quot;events&quot;,<br>      &quot;ingresses&quot;,<br>      &quot;ingresses/status&quot;,<br>      &quot;services&quot;,<br>    ]<br>    verbs = [<br>      &quot;create&quot;,<br>      &quot;get&quot;,<br>      &quot;list&quot;,<br>      &quot;update&quot;,<br>      &quot;watch&quot;,<br>      &quot;patch&quot;,<br>    ]<br>  }<br>  rule {<br>    api_groups = [<br>      &quot;&quot;,<br>      &quot;extensions&quot;,<br>    ]<br>    resources = [<br>      &quot;nodes&quot;,<br>      &quot;pods&quot;,<br>      &quot;secrets&quot;,<br>      &quot;services&quot;,<br>      &quot;namespaces&quot;,<br>    ]<br>    verbs = [<br>      &quot;get&quot;,<br>      &quot;list&quot;,<br>      &quot;watch&quot;,<br>    ]<br>  }<br>}<br>resource &quot;kubernetes_cluster_role_binding&quot; &quot;aws-load-balancer-controller-cluster-role-binding&quot; {<br>  depends_on = [aws_eks_cluster.eks-cluster , aws_eks_node_group.node-group-private ]<br>  metadata {<br>    name = &quot;aws-load-balancer-controller&quot;<br>    labels = {<br>      &quot;app.kubernetes.io/name&quot;       = &quot;aws-load-balancer-controller&quot;<br>      &quot;app.kubernetes.io/managed-by&quot; = &quot;terraform&quot;<br>    }<br>  }<br>  role_ref {<br>    api_group = &quot;rbac.authorization.k8s.io&quot;<br>    kind      = &quot;ClusterRole&quot;<br>    name      = kubernetes_cluster_role.aws-load-balancer-controller-cluster-role.metadata[0].name<br>  }<br>  subject {<br>    api_group = &quot;&quot;<br>    kind      = &quot;ServiceAccount&quot;<br>    name      = kubernetes_service_account.aws-load-balancer-controller-service-account.metadata[0].name<br>    namespace = kubernetes_service_account.aws-load-balancer-controller-service-account.metadata[0].namespace<br>  }<br>}</pre><p><strong>Helm Release for ALB ingress controller and EBS CSI driver and Metrics Server</strong></p><pre>resource &quot;helm_release&quot; &quot;alb-ingress-controller&quot; {<br>  <br>  depends_on = [<br>    aws_eks_cluster.eks-cluster ,<br>    aws_eks_node_group.node-group-private ,<br>    kubernetes_cluster_role_binding.aws-load-balancer-controller-cluster-role-binding,<br>    kubernetes_service_account.aws-load-balancer-controller-service-account , <br>    kubernetes_secret.aws-load-balancer-controller , <br>    helm_release.karpenter , <br>    kubectl_manifest.karpenter-provisioner ]<br>  <br>  name       = &quot;alb-ingress-controller&quot;<br>  repository = &quot;&lt;https://aws.github.io/eks-charts&gt;&quot;<br>  version = &quot;1.4.7&quot;<br>  chart      = &quot;aws-load-balancer-controller&quot;<br>  namespace =  &quot;kube-system&quot;<br>  values = [data.template_file.alb-ingress-values.rendered]<br><br>set {<br>    name  = &quot;serviceAccount.create&quot;<br>    value = &quot;false&quot;<br>  }<br>  set {<br>    name  = &quot;serviceAccount.name&quot;<br>    value = &quot;${kubernetes_service_account.aws-load-balancer-controller-service-account.metadata[0].name}&quot;<br>  }<br>}<br><br>resource &quot;helm_release&quot; &quot;aws-ebs-csi-driver&quot; {<br>  depends_on = [ aws_eks_cluster.eks-cluster , aws_eks_node_group.node-group-private , helm_release.karpenter , kubectl_manifest.karpenter-provisioner , aws_iam_role.ebs-csi ]<br>  name       = &quot;aws-ebs-csi-driver&quot;<br>  repository = &quot;&lt;https://kubernetes-sigs.github.io/aws-ebs-csi-driver&gt;&quot;<br>  chart      = &quot;aws-ebs-csi-driver&quot;<br>  namespace =  &quot;kube-system&quot;<br>  create_namespace = true<br>  values = [data.template_file.ebs-csi-driver-values.rendered]<br>}<br><br>resource &quot;helm_release&quot; &quot;metrics-server&quot; {<br>    depends_on = [helm_release.karpenter , kubectl_manifest.karpenter-provisioner ]<br>    name        = &quot;metrics-server&quot;<br>    chart       = &quot;metrics-server&quot;<br>    repository  = &quot;&lt;https://kubernetes-sigs.github.io/metrics-server/&gt;&quot;<br>    version     = &quot;3.8.2&quot;<br>    namespace   = &quot;kube-system&quot;<br>    description = &quot;Metric server helm Chart deployment configuration&quot;<br>}</pre><p><strong>IAM role and policies for Karpenter controller</strong></p><pre>data &quot;aws_iam_policy_document&quot; &quot;karpenter_controller_assume_role_policy&quot; {<br>  statement {<br>    actions = [&quot;sts:AssumeRoleWithWebIdentity&quot;]<br>    effect  = &quot;Allow&quot;<br>    condition {<br>      test     = &quot;StringEquals&quot;<br>      variable = &quot;${replace(data.aws_eks_cluster.cluster.identity[0].oidc[0].issuer, &quot;https://&quot;, &quot;&quot;)}:sub&quot;<br>      values   = [&quot;system:serviceaccount:karpenter:karpenter&quot;]<br>    }<br>    condition {<br>      test     = &quot;StringEquals&quot;<br>      variable = &quot;${replace(data.aws_eks_cluster.cluster.identity[0].oidc[0].issuer, &quot;https://&quot;, &quot;&quot;)}:aud&quot;<br>      values   = [&quot;sts.amazonaws.com&quot;]<br>    }<br>    principals {<br>      identifiers = [<br>        &quot;arn:aws:iam::${data.aws_caller_identity.current.account_id}:oidc-provider/${replace(data.aws_eks_cluster.cluster.identity[0].oidc[0].issuer, &quot;https://&quot;, &quot;&quot;)}&quot;<br>      ]<br>      type = &quot;Federated&quot;<br>    }<br>  }<br>}<br><br>data &quot;aws_iam_policy_document&quot; &quot;karpenter&quot; {<br>  statement {<br>    resources = [&quot;*&quot;]<br>    actions   = [&quot;ec2:DescribeImages&quot;, &quot;ec2:RunInstances&quot;, &quot;ec2:DescribeSubnets&quot;, &quot;ec2:DescribeSecurityGroups&quot;, &quot;ec2:DescribeLaunchTemplates&quot;, &quot;ec2:DescribeInstances&quot;, &quot;ec2:DescribeInstanceTypes&quot;, &quot;ec2:DescribeInstanceTypeOfferings&quot;, &quot;ec2:DescribeAvailabilityZones&quot;, &quot;ec2:DeleteLaunchTemplate&quot;, &quot;ec2:CreateTags&quot;, &quot;ec2:CreateLaunchTemplate&quot;, &quot;ec2:CreateFleet&quot;, &quot;ec2:DescribeSpotPriceHistory&quot;, &quot;pricing:GetProducts&quot;, &quot;ssm:GetParameter&quot;]<br>    effect    = &quot;Allow&quot;<br>  }<br>  statement {<br>    resources = [&quot;*&quot;]<br>    actions   = [&quot;ec2:TerminateInstances&quot;, &quot;ec2:DeleteLaunchTemplate&quot; , &quot;ec2:RequestSpotInstances&quot; , &quot;ec2:DescribeInstanceStatus&quot; , &quot;iam:CreateServiceLinkedRole&quot; , &quot;iam:ListRoles&quot; , &quot;iam:ListInstanceProfiles&quot;]<br>    effect    = &quot;Allow&quot;<br>    # Make sure Karpenter can only delete nodes that it has provisioned<br>    condition {<br>      test     = &quot;StringEquals&quot;<br>      values   = [var.eks_cluster_name]<br>      variable = &quot;ec2:ResourceTag/karpenter.sh/discovery&quot;<br>    }<br>  }<br>  statement {<br>    resources = [data.aws_eks_cluster.cluster.arn]<br>    actions   = [&quot;eks:DescribeCluster&quot;]<br>    effect    = &quot;Allow&quot;<br>  }<br>  statement {<br>    resources = [element(aws_iam_role.NodeGroupRole.*.arn,0)]<br>    actions   = [&quot;iam:PassRole&quot;]<br>    effect    = &quot;Allow&quot;<br>  }<br>  # Optional: Interrupt Termination Queue permissions, provided by AWS SQS<br>  statement {<br>    resources = [aws_sqs_queue.karpenter.arn]<br>    actions   = [&quot;sqs:DeleteMessage&quot;, &quot;sqs:GetQueueUrl&quot;, &quot;sqs:GetQueueAttributes&quot;, &quot;sqs:ReceiveMessage&quot;]<br>    effect    = &quot;Allow&quot;<br>  }<br>}<br>resource &quot;aws_iam_role&quot; &quot;karpenter_controller&quot; {<br>  description        = &quot;IAM Role for Karpenter Controller (pod) to assume&quot;<br>  assume_role_policy = data.aws_iam_policy_document.karpenter_controller_assume_role_policy.json<br>  name               = &quot;karpenter-controller&quot;<br>  inline_policy {<br>    policy = data.aws_iam_policy_document.karpenter.json<br>    name   = &quot;karpenter&quot;<br>  }<br>  depends_on = [data.aws_iam_policy_document.karpenter_controller_assume_role_policy , data.aws_iam_policy_document.karpenter]<br>}</pre><h4><strong>Instance Profile for Karpenter</strong></h4><pre>## Karpenter Instance Profile<br><br>resource &quot;aws_iam_instance_profile&quot; &quot;karpenter&quot; {<br>  name = &quot;karpenter-instance-profile&quot;<br>  role = element(aws_iam_role.NodeGroupRole.*.name,0)<br>  depends_on = [ aws_iam_role.NodeGroupRole  ]<br>}</pre><h4><strong>Handling Interruption For Spot Instance via SQS queue and Event Bridge rules</strong></h4><pre># SQS Queue<br><br>resource &quot;aws_sqs_queue&quot; &quot;karpenter&quot; {<br>  message_retention_seconds = 300<br>  name                      = &quot;${var.cluster_name}-karpenter-sqs-queue&quot;<br>}<br># Node termination queue policy<br>resource &quot;aws_sqs_queue_policy&quot; &quot;karpenter&quot; {<br>  policy    = data.aws_iam_policy_document.node_termination_queue.json<br>  queue_url = aws_sqs_queue.karpenter.url<br>}<br>data &quot;aws_iam_policy_document&quot; &quot;node_termination_queue&quot; {<br>  statement {<br>    resources = [aws_sqs_queue.karpenter.arn]<br>    sid       = &quot;SQSWrite&quot;<br>    actions   = [&quot;sqs:SendMessage&quot;]<br>    principals {<br>      type        = &quot;Service&quot;<br>      identifiers = [&quot;events.amazonaws.com&quot;, &quot;sqs.amazonaws.com&quot;]<br>    }<br>  }<br>}<br>resource &quot;aws_cloudwatch_event_rule&quot; &quot;scheduled_change_rule&quot; {<br>  name        = &quot;ScheduledChangeRule&quot;<br>  description = &quot;AWS Health Event&quot;<br>  event_pattern = jsonencode({<br>    source      = [&quot;aws.health&quot;]<br>    detail_type = [&quot;AWS Health Event&quot;]<br>  })<br>}<br>resource &quot;aws_cloudwatch_event_rule&quot; &quot;spot_interruption_rule&quot; {<br>  name        = &quot;SpotInterruptionRule&quot;<br>  description = &quot;EC2 Spot Instance Interruption Warning&quot;<br>  event_pattern = jsonencode({<br>    source      = [&quot;aws.ec2&quot;]<br>    detail_type = [&quot;EC2 Spot Instance Interruption Warning&quot;]<br>  })<br>}<br>resource &quot;aws_cloudwatch_event_rule&quot; &quot;rebalance_rule&quot; {<br>  name        = &quot;RebalanceRule&quot;<br>  description = &quot;EC2 Instance Rebalance Recommendation&quot;<br>  event_pattern = jsonencode({<br>    source      = [&quot;aws.ec2&quot;]<br>    detail_type = [&quot;EC2 Instance Rebalance Recommendation&quot;]<br>  })<br>}<br>resource &quot;aws_cloudwatch_event_rule&quot; &quot;instance_state_change_rule&quot; {<br>  name        = &quot;InstanceStateChangeRule&quot;<br>  description = &quot;EC2 Instance State-change Notification&quot;<br>  event_pattern = jsonencode({<br>    source      = [&quot;aws.ec2&quot;]<br>    detail_type = [&quot;EC2 Instance State-change Notification&quot;]<br>  })<br>}<br>resource &quot;aws_cloudwatch_event_target&quot; &quot;scheduled_change_rule&quot; {<br>  rule      = aws_cloudwatch_event_rule.scheduled_change_rule.name<br>  arn       = aws_sqs_queue.karpenter.arn<br>}<br>resource &quot;aws_cloudwatch_event_target&quot; &quot;spot_interruption_rule&quot; {<br>  rule      = aws_cloudwatch_event_rule.spot_interruption_rule.name<br>  arn       = aws_sqs_queue.karpenter.arn<br>}<br>resource &quot;aws_cloudwatch_event_target&quot; &quot;rebalance_rule&quot; {<br>  rule      = aws_cloudwatch_event_rule.rebalance_rule.name<br>  arn       = aws_sqs_queue.karpenter.arn<br>}<br>resource &quot;aws_cloudwatch_event_target&quot; &quot;instance_state_change_rule&quot; {<br>  rule      = aws_cloudwatch_event_rule.instance_state_change_rule.name<br>  arn       = aws_sqs_queue.karpenter.arn<br>}</pre><h4><strong>Template File ( values.yml ) for Karpenter</strong></h4><pre>data &quot;template_file&quot; &quot;karpenter&quot; {<br>  template = &lt;&lt;EOF<br>serviceAccount:<br>   annotations:<br>       eks.amazonaws.com/role-arn: &quot;${aws_iam_role.karpenter_controller.arn}&quot;<br>settings:<br>  aws:<br>    clusterName: &quot;${data.aws_eks_cluster.cluster.id}&quot;<br>    clusterEndpoint: &quot;${data.aws_eks_cluster.cluster.endpoint}&quot;<br>    defaultInstanceProfile: &quot;${aws_iam_instance_profile.karpenter.name}&quot;<br>    interruptionQueueName: &quot;${var.cluster_name}-karpenter-sqs-queue&quot;<br>   EOF<br>}</pre><h4><strong>Helm release for Karpenter</strong></h4><pre>resource &quot;helm_release&quot; &quot;karpenter&quot; {<br>  namespace        = &quot;karpenter&quot;<br>  create_namespace = true<br>  name                = &quot;karpenter&quot;<br>  repository          = &quot;oci://public.ecr.aws/karpenter&quot;<br>  repository_username = data.aws_ecrpublic_authorization_token.token.user_name<br>  repository_password = data.aws_ecrpublic_authorization_token.token.password<br>  chart               = &quot;karpenter&quot;<br>  version    = &quot;v0.27.0&quot;  <br>  values = [data.template_file.karpenter.rendered]<br>  # set {<br>  #   name  = &quot;serviceAccount.annotations.eks\\.amazonaws\\.com/role-arn&quot;<br>  #   value = &quot;${aws_iam_role.karpenter_controller.arn}&quot;<br>  # }<br> # set {<br>  #   name  = &quot;settings.aws.clusterName&quot;<br>  #   value = data.aws_eks_cluster.cluster.id<br>  # }<br>  # set {<br>  #   name  = &quot;settings.aws.clusterEndpoint&quot;<br>  #   value = data.aws_eks_cluster.cluster.endpoint<br>  # }<br>  # set {<br>  #   name  = &quot;settings.aws.defaultInstanceProfile&quot;<br>  #   value = aws_iam_instance_profile.karpenter.name<br>  # }<br>  # set {<br>  #   name  = &quot;settings.aws.interruptionQueueName&quot;<br>  #   value =  &quot;${var.cluster_name}-karpenter-sqs-queue&quot;<br>  # }<br>  depends_on = [ aws_eks_cluster.eks-cluster , aws_eks_node_group.node-group-private , aws_iam_role.karpenter_controller , aws_iam_instance_profile.karpenter , aws_sqs_queue.karpenter ]<br>}</pre><blockquote>Not finished yet !! We need Provisioners installed which decides what type of instance to bring up based on the workload.</blockquote><p>Provisioners are CRDs that Karpenter uses to provision new nodes. New nodes are brought up based on the pods that are waiting to be scheduled and their scheduling constraints</p><p><strong>Configuring Default Karpenter Provisioner</strong></p><pre>resource &quot;kubectl_manifest&quot; &quot;karpenter-provisioner&quot; {<br>    depends_on = [ helm_release.karpenter , aws_eks_cluster.eks-cluster , aws_eks_node_group.node-group-private]<br>    yaml_body = &lt;&lt;YAML<br>apiVersion: karpenter.sh/v1alpha5<br>kind: Provisioner<br>metadata:<br>  name: karpenter-default<br>  namespace: karpenter<br>spec:<br>  provider:<br>    securityGroupSelector:<br>      karpenter.sh/discovery: &quot;${var.cluster_name}&quot;<br>    subnetSelector:<br>      karpenter.sh/discovery: &quot;${var.cluster_name}&quot;<br>    tags:<br>      karpenter.sh/discovery: &quot;${var.cluster_name}&quot;<br>  requirements:<br>    - key: karpenter.sh/capacity-type<br>      operator: In<br>      values: [&quot;spot&quot;]<br>    - key: &quot;node.kubernetes.io/instance-type&quot;<br>      operator: In<br>      values: [&quot;t3a.micro&quot; , &quot;t3a.medium&quot; , &quot;t3a.large&quot; ]<br>    - key: &quot;topology.kubernetes.io/zone&quot;<br>      operator: In<br>      values: [&quot;us-east-1a&quot;, &quot;us-east-1b&quot; , &quot;us-east-1c&quot;]<br>    - key: created-by<br>      operator: In<br>      values: [&quot;karpenter&quot;]<br>  ttlSecondsAfterEmpty: 30<br>YAML<br>}</pre><p><strong>Note:</strong> securityGroupSelector and subnetSelector — These are used by Karpenter to identify which subnets and security groups should be used for the new nodes. When you bring up your EKS cluster you should add the respective tags to your private_subnets and to your node_security_group. Not setting these correctly can cause Karpenter to not bring up nodes or the nodes that are brought up can have difficulties trying to join the cluster.</p><p>The constraints ttlSecondsUntilExpired defines the node expiry so a newer node will be provisioned, and ttlSecondsAfterEmpty defines when to delete a node since the last workload stops running. (<strong>Note:</strong> DaemonSets are not taken into account.)</p><h3>Deploying via Terraform Cloud !!!</h3><p>I am deploying the EKS Cluster to the AWS via Terraform Cloud . I have workspaces and made connections to the repository and updated variables.</p><p><strong>Workspace Run Overview:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yka10VtT30AlTH_xbqmPvA.png" /></figure><p><strong>Workspace Variables Overview:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhJDZGTRZAIShs2EzllUXw.png" /></figure><p><strong>Workspace Planned:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9NHhNuf8xnN5cTShNsz1A.png" /></figure><p><strong>Workspace Applied:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgCKCc_Tj0XbbzX-AP4apQ.png" /></figure><h3>Testing it !! Its Time for Action</h3><p><strong>Updating the Kubeconfig File</strong></p><pre>aws eks update-kubeconfig --region us-east-1 --name karpenter-demo</pre><p><strong>Listing all Pods in the Cluster</strong></p><pre>kubectl get pods -A</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-W1j3ra_Bna-jkROb5big.png" /></figure><p><strong>Listing all resources in Karpenter Namespace</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8DlFpxkqBGYMoA4C-QJ1w.png" /><figcaption>kubectl get all -n karpenter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8kBU3Ex7UxKZmgZBWogvQ.png" /><figcaption>kubectl get provisioner -n karpenter</figcaption></figure><pre>kubectl create deployment nginx --image=nginx<br>kubectl set resources deployment nginx --requests=cpu=100m,memory=256Mi<br>kubectl scale deployment nginx --replicas 12</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTq8XsuXpwPc4NqteGJusw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoYOUNQlEqa3fSb1NiwkAQ.png" /><figcaption>kubectl logs pods/karpenter-5868c87959–8dxmw -n karpenter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWFLJAtY-bqoYRbcuLBb2w.png" /><figcaption>kubectl logs pods/karpenter-5868c87959–8dxmw -n karpenter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R49gitYrXxmJD4RMJuEm0g.png" /><figcaption>kubectl get nodes -o wide</figcaption></figure><p>We can see a new node got provisioned . To verify that it created a spot instance lets go to the console and see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4mqBB4sotRQ2r2sGOygLQ.png" /></figure><p>Now lets scale down to see what happens.</p><pre>kubectl scale deployment nginx --replicas 1</pre><p>Immediately after that :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ft-DiyLDZEkCOUN7DjKB_w.png" /></figure><p>Lets check console whats happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYZQHZPyDrJXoS_oO9X14Q.png" /></figure><p>This confirms our setup was successfully completed !!</p><p>Thank you for reading my article , have a nice day and keep learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b68bbd64f23c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/techbeatly/maximizing-cost-efficiency-with-karpenter-setting-up-eks-cluster-v1-24-b68bbd64f23c">Maximizing Cost-Efficiency  with Karpenter : Setting Up EKS Cluster (v1.24)</a> was originally published in <a href="https://medium.com/techbeatly">techbeatly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>