<?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"><channel><title><![CDATA[Bits in Skeweres]]></title><description><![CDATA[Khalti is a Digital wallet based in Nepal and we are here to discuss things that we do around our engineering.]]></description><link>https://khalti.engineering</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1684691193467/6VaNaQWvP.png</url><title>Bits in Skeweres</title><link>https://khalti.engineering</link></image><generator>RSS for Node</generator><lastBuildDate>Mon, 07 Sep 2026 17:36:53 GMT</lastBuildDate><atom:link href="https://khalti.engineering/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Examination Preparation Materials - Chapter 07]]></title><description><![CDATA[The Fintech industry encompasses a broad range of innovative technologies applied to financial services. Here are some key areas within Fintech:

Payments: This area focuses on electronic payments, including mobile wallets, digital money transfers, o...]]></description><link>https://khalti.engineering/examination-preparation-materials-chapter-07</link><guid isPermaLink="true">https://khalti.engineering/examination-preparation-materials-chapter-07</guid><category><![CDATA[career in fintech engineering]]></category><category><![CDATA[institute-of-engineering]]></category><category><![CDATA[applied-fintech-engineering]]></category><category><![CDATA[pulchowk-campus]]></category><category><![CDATA[khalti]]></category><category><![CDATA[examination preparation materials]]></category><dc:creator><![CDATA[Dhruba Adhikari]]></dc:creator><pubDate>Thu, 28 Mar 2024 11:14:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/mpN7xjKQ_Ns/upload/b6c507d0073478fd81bdc0ccccd5e6eb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The Fintech industry encompasses a broad range of innovative technologies applied to financial services. Here are some key areas within Fintech:</p>
<ul>
<li><p><strong>Payments:</strong> This area focuses on electronic payments, including mobile wallets, digital money transfers, online payment gateways, and contactless payment solutions. It aims to make transactions faster, more secure, and more convenient.</p>
</li>
<li><p><strong>Lending &amp; Alternative Finance:</strong> This involves platforms that use technology to streamline loan applications, credit scoring, and alternative financing solutions like peer-to-peer lending and crowdfunding.</p>
</li>
<li><p><strong>Wealth Management &amp; Robo-advisors:</strong> Fintech companies in this area use technology to automate investment management and financial planning. Robo-advisors are a prime example, offering automated investment strategies based on user profiles.</p>
</li>
<li><p><strong>RegTech:</strong> This sector focuses on regulatory technology solutions for financial institutions. It helps them comply with complex regulations related to Anti-Money Laundering (AML), Know Your Customer (KYC), and data security.</p>
</li>
</ul>
<h3 id="heading-understanding-risk-and-risk-based-scoring-in-decision-engines"><strong>Understanding Risk and Risk-Based Scoring in Decision Engines</strong></h3>
<p>In finance, risk refers to the <strong>potential for loss or negative outcomes</strong> associated with an investment or financial decision. Factors like creditworthiness, market fluctuations, and operational failures can all contribute to risk.</p>
<ul>
<li><strong>Risk-Based Scoring:</strong> This technique assigns a numerical score to an individual or entity based on their risk profile. It considers various factors like credit history, income, debt-to-income ratio, and transaction patterns. Decision engines utilize these scores to automate decisions like loan approvals, fraud detection, and insurance eligibility.</li>
</ul>
<p><strong>Example:</strong> When applying for a loan, a bank's decision engine might use your risk score to determine your loan eligibility, interest rate, and loan amount.</p>
<p>Here are some additional points:</p>
<ul>
<li><p>Risk scores are not foolproof and can be influenced by factors outside an individual's control.</p>
</li>
<li><p>Fairness and responsible use of risk-based scoring are important considerations.</p>
</li>
</ul>
<h3 id="heading-risk-residue">Risk residue</h3>
<p>Residual risk refers to the amount of risk that remains after mitigation efforts have been implemented. It's essentially the <strong>unavoidable</strong> level of risk that persists even after you've taken steps to reduce the overall risk. This can also be regarded as the level of risk that is accepted by a company.</p>
<h3 id="heading-risk-grading-examples-for-a-mobile-wallet">Risk Grading Examples for a Mobile Wallet</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Risk Category</td><td>Level / Risk Description</td><td>Potential Impact</td><td>Mitigation Strategies</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Security</strong></td><td><strong>High :</strong></td><td></td><td></td></tr>
<tr>
<td>Unauthorized access to user accounts and funds.</td><td>Loss of funds, identity theft, reputational damage.</td><td>- Strong user authentication (multi-factor authentication).</td><td></td></tr>
<tr>
<td>- Secure data encryption at rest and in transit.</td><td></td><td></td><td></td></tr>
<tr>
<td>- Regular penetration testing and vulnerability assessments.</td><td></td><td></td><td></td></tr>
<tr>
<td>- Secure coding practices.</td><td></td><td></td><td></td></tr>
<tr>
<td><strong>Transaction Processing</strong></td><td><strong>Medium :</strong></td><td></td><td></td></tr>
<tr>
<td>Failure to process transactions accurately or timely.</td><td>Financial loss for users and merchants, inconvenience.</td><td>- Robust transaction processing infrastructure with redundancy.</td><td></td></tr>
<tr>
<td>- Automated transaction monitoring for errors.</td><td></td><td></td><td></td></tr>
<tr>
<td>- Clear communication to users in case of transaction delays.</td><td></td><td></td><td></td></tr>
<tr>
<td><strong>Data Privacy</strong></td><td><strong>High :</strong></td><td></td><td></td></tr>
<tr>
<td>User data breach or unauthorized access.</td><td>Regulatory fines, reputational damage, loss of user trust.</td><td>- Implement data minimization principles (collect only necessary data). - Secure data storage practices (encryption). - Regular data security training for employees.</td><td></td></tr>
<tr>
<td>- Strict access controls to user data.</td><td></td><td></td><td></td></tr>
<tr>
<td><strong>System Availability</strong></td><td><strong>Medium :</strong></td><td></td><td></td></tr>
<tr>
<td>Outage or disruption of wallet services.</td><td>User inconvenience, potential loss of revenue.</td><td>- High availability infrastructure with disaster recovery plan.</td><td></td></tr>
<tr>
<td>- Regular system backups and testing.</td><td></td><td></td><td></td></tr>
<tr>
<td>- User communication during outages.</td><td></td><td></td><td></td></tr>
<tr>
<td><strong>Integration Issues</strong></td><td><strong>Medium :</strong></td><td></td><td></td></tr>
<tr>
<td>Difficulties integrating with external payment networks or services.</td><td>Delays in launching features, potential compatibility problems.</td><td>- Thorough testing of integrations before deployment.</td><td></td></tr>
<tr>
<td>- Clear technical specifications for integrations.</td><td></td><td></td><td></td></tr>
<tr>
<td>- Proactive communication with partner companies.</td><td></td><td></td></tr>
</tbody>
</table>
</div><h2 id="heading-artificial-intelligence-in-fintech-engineering">Artificial Intelligence in Fintech Engineering</h2>
<p>Here are 10 scopes of Artificial Intelligence (AI) in Fintech engineering, expanding on the three mentioned previously:</p>
<p><strong>Personalized Finance and Customer Experience:</strong></p>
<ol>
<li><p><strong>Robo-advisors &amp; Algorithmic Wealth Management:</strong> AI algorithms can analyze user data, financial goals, and market trends to provide personalized investment recommendations and automate wealth management tasks.</p>
</li>
<li><p><strong>Dynamic Credit Scoring &amp; Loan Underwriting:</strong> AI can go beyond traditional credit scores by analyzing alternative data sources (e.g., cash flow, spending habits) to offer more inclusive and personalized loan options.</p>
</li>
<li><p><strong>Chatbots &amp; Virtual Assistants:</strong> AI-powered chatbots can provide 24/7 customer support, answer financial questions, and personalize product recommendations, enhancing the overall customer experience.</p>
</li>
</ol>
<p><strong>Risk Management and Fraud Detection:</strong></p>
<ol start="4">
<li><p><strong>Anomaly Detection &amp; Fraudulent Transaction Identification:</strong> AI can analyze vast amounts of transaction data in real-time to identify suspicious patterns and prevent fraudulent activities.</p>
</li>
<li><p><strong>Risk Assessment &amp; Creditworthiness Evaluation:</strong> AI models can analyze financial data and user behavior to assess creditworthiness and predict potential loan defaults, allowing for more informed lending decisions.</p>
</li>
<li><p><strong>Cybersecurity Threat Detection:</strong> AI can continuously monitor network activity and user behavior to identify and prevent cyber threats like phishing attacks or account takeovers.</p>
</li>
<li><p><strong>KYC and Liveliness</strong> : KYC is a regulatory requirement for financial institutions to verify the identity of their customers. Liveness checks are a type of KYC verification that aims to confirm a user is a real person, not a synthetic identity created for fraudulent purposes. Facial recognition, gestures like blinks, movements etc are used to identify the liveliness of a person.</p>
</li>
</ol>
<p><strong>Market Analysis and Algorithmic Trading:</strong></p>
<ol start="7">
<li><p><strong>Algorithmic Trading Strategies:</strong> AI algorithms can analyze market data, news sentiment, and social media trends to generate high-frequency trading strategies and potentially identify profitable opportunities.</p>
</li>
<li><p><strong>Market Prediction &amp; Portfolio Optimization:</strong> AI can be used to analyze historical data and market trends to make predictions about future market movements and help optimize investment portfolios.</p>
</li>
<li><p><strong>Regulatory Compliance &amp; Anti-Money Laundering (AML):</strong> AI can be used to analyze transactions and identify patterns that might be indicative of money laundering or other illegal activities, assisting with regulatory compliance.</p>
</li>
</ol>
<p><strong>Additionally:</strong></p>
<ol start="10">
<li><strong>Insurtech &amp; Personalized Insurance Products:</strong> AI can be used to personalize insurance products and pricing based on individual risk profiles and behavior, leading to more efficient and cost-effective insurance solutions.</li>
</ol>
<p>These are just a few examples, and as AI technology continues to evolve, we can expect even more innovative applications to emerge within the Fintech industry.</p>
]]></content:encoded></item><item><title><![CDATA[Examination Preparation Materials - Chapter 06]]></title><description><![CDATA[What is version control ?
Version control is a system that tracks changes to a set of files over time. It's essentially a way to record the history of your files, allowing you to see who made what changes, when they were made, and revert back to prev...]]></description><link>https://khalti.engineering/examination-preparation-materials-chapter-06</link><guid isPermaLink="true">https://khalti.engineering/examination-preparation-materials-chapter-06</guid><category><![CDATA[pulchowk-campus]]></category><category><![CDATA[institute-of-engineering]]></category><category><![CDATA[applied-fintech-engineering]]></category><category><![CDATA[examination preparation materials]]></category><dc:creator><![CDATA[Dhruba Adhikari]]></dc:creator><pubDate>Thu, 28 Mar 2024 11:00:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/vIQDv6tUHYk/upload/d5729cffd4b13bffc0fd70c5ef92b3a9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-what-is-version-control">What is version control ?</h1>
<p>Version control is a system that tracks changes to a set of files over time. It's essentially a way to record the history of your files, allowing you to see who made what changes, when they were made, and revert back to previous versions if needed. Version control is particularly important in software development, where multiple people might be working on the same codebase, but it can be useful for any kind of project that involves managing revisions of documents, design files, or other digital assets.</p>
<p>There are two main types of version control systems (VCS) with distinct characteristics:</p>
<h3 id="heading-centralized-version-control-systems-cvcs"><strong>Centralized Version Control Systems (CVCS)</strong></h3>
<ol>
<li><p><strong>Centralized Repository:</strong> CVCS stores all versions of the files in a single central server. This server acts as the one source of truth for the project.</p>
</li>
<li><p><strong>Checkout &amp; Check-in:</strong> Developers need to "check out" files from the central server to make changes locally. Once edits are complete, they "check in" the modified files back to the server. This ensures only one person can edit a file at a time, preventing conflicts.</p>
</li>
<li><p><strong>Examples:</strong> Subversion (SVN) is a popular example of a CVCS.</p>
</li>
</ol>
<h3 id="heading-distributed-version-control-systems-dvcs"><strong>Distributed Version Control Systems (DVCS)</strong></h3>
<ol>
<li><p><strong>Distributed Repositories:</strong> DVCS doesn't rely on a single central server. Each developer has a complete copy of the entire version history on their local machine. This local copy is called a "clone" of the main repository, which can be hosted remotely for collaboration.</p>
</li>
<li><p><strong>Offline Work:</strong> Since developers have a complete history locally, they can work on changes even without an internet connection. This allows for greater flexibility and offline development.</p>
</li>
<li><p><strong>Branching &amp; Merging:</strong> DVCS excels at branching, where developers can create isolated copies of the codebase to work on features or bug fixes independently. These branches can then be merged back into the main codebase when ready. This facilitates collaboration and experimentation.</p>
</li>
<li><p><strong>Examples:</strong> Git is the most popular DVCS used today. Mercurial is another example.</p>
</li>
</ol>
<p>Here's a table summarizing the key differences:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>Centralized Version Control (CVCS)</td><td>Distributed Version Control (DVCS)</td></tr>
</thead>
<tbody>
<tr>
<td>Repository Location</td><td>Central Server</td><td>Distributed (Local Machine &amp; Remote)</td></tr>
<tr>
<td>Offline Work</td><td>Limited</td><td>Possible</td></tr>
<tr>
<td>Checkout/Check-in</td><td>Required</td><td>Not Applicable</td></tr>
<tr>
<td>Branching</td><td>Less Flexible</td><td>Highly Flexible</td></tr>
<tr>
<td>Collaboration</td><td>Requires Central Server Access</td><td>Enables Offline Collaboration</td></tr>
<tr>
<td>Popular Examples</td><td>Subversion (SVN)</td><td>Git, Mercurial</td></tr>
</tbody>
</table>
</div><p>Choosing between CVCS and DVCS depends on your project needs. CVCS can be simpler for small teams with a stable development environment. However, for most modern software development projects, the flexibility and offline capabilities of DVCS like Git make them the preferred choice.</p>
<h2 id="heading-git-basics">Git Basics</h2>
<p>Git is a popular distributed version control system (DVCS) used for tracking changes in computer files. It's particularly helpful for software development projects where multiple people collaborate on the codebase.</p>
<p>Learn more about git from</p>
<ol>
<li><p>Official Site - <a target="_blank" href="https://git-scm.com/">https://git-scm.com/</a></p>
</li>
<li><p>Github.com - <a target="_blank" href="https://docs.github.com/en/get-started/start-your-journey/git-and-github-learning-resources">https://docs.github.com/en/get-started/start-your-journey/git-and-github-learning-resources</a></p>
</li>
<li><p>Learn git branching - <a target="_blank" href="https://learngitbranching.js.org/">https://learngitbranching.js.org/</a></p>
</li>
</ol>
<h3 id="heading-git-pull-git-fetch-git-merge-git-rebase">Git Pull, Git Fetch, Git merge, Git Rebase</h3>
<p>All of these are git workflow commands with specific usecases.</p>
<ul>
<li><p><strong>Git Fetch:</strong> This command downloads the latest changes from a remote repository but doesn't automatically merge them into your local branch. The fetched changes are stored locally for you to review and then decide how to integrate them (often using <code>git merge</code> later).</p>
</li>
<li><p><strong>Git Merge:</strong> This command manually integrates changes from another branch (local or remote) into your current branch. If there are conflicts (overlapping changes in the same file), you'll need to resolve them manually before completing the merge.</p>
</li>
<li><p><strong>Git Pull:</strong> This command <strong>combines two actions</strong>: <code>git fetch</code> and <code>git merge</code>. It retrieves the latest changes from a remote repository (usually the one you push your commits to) and attempts to automatically merge them into your local branch. It's a convenient shortcut for updating your local branch with the latest upstream changes.</p>
</li>
<li><p><strong>Git Rebase:</strong> This command rewrites your local commit history. It takes your current branch and replays your commits on top of the latest remote branch head. This can result in a cleaner linear commit history, but it can also be risky if you've already shared your local branch with others as it rewrites history.</p>
</li>
</ul>
<h3 id="heading-explanation-by-example">Explanation by example</h3>
<p>Imagine you're working on a feature branch for a project called "add_search" that adds a search bar functionality. You have two commits in your branch:</p>
<ul>
<li><p>Commit 1: Added basic search functionality to the code.</p>
</li>
<li><p>Commit 2: Improved the search bar UI.</p>
</li>
</ul>
<p>In the meantime, the main branch (often called "master") has received bug fixes from another developer (Commit X).</p>
<p>Here's how rebase, squash, and merge would handle integrating your "add_search" branch with the updated main branch:</p>
<p><strong>Rebase:</strong></p>
<ol>
<li><p>You use <code>git fetch</code> to download the latest changes from the remote repository (including Commit X on main branch).</p>
</li>
<li><p>You run <code>git rebase main</code>. This replays your commits (Commit 1 and Commit 2) on top of the latest main branch (which now includes Commit X).</p>
</li>
</ol>
<p><strong>Result:</strong> Your local "add_search" branch now has a linear history with three commits: Commit X (from main branch), your Commit 1 (modified to reflect the rebased position), and your Commit 2 (also rebased).</p>
<p><strong>Squash:</strong></p>
<ol>
<li><p>You use <code>git fetch</code> to download the latest changes.</p>
</li>
<li><p>You run <code>git merge main</code> to initiate a merge with the main branch.</p>
</li>
<li><p>Git identifies a merge conflict (since both branches might have modified the same files). You resolve the conflict manually.</p>
</li>
<li><p>Instead of creating a regular merge commit, you use the <code>--squash</code> option with <code>git commit</code> to combine your two commits from the "add_search" branch into a single commit with a new message summarizing the changes.</p>
</li>
</ol>
<p><strong>Result:</strong> Your local "add_search" branch has a single commit that integrates the search functionality and UI improvements, along with the bug fix from the main branch (Commit X) reflected as the parent commit.</p>
<p><strong>Merge:</strong></p>
<ol>
<li><p>You use <code>git fetch</code> to download the latest changes.</p>
</li>
<li><p>You run <code>git merge main</code> to integrate the main branch into your "add_search" branch.</p>
</li>
<li><p>Git might identify a merge conflict that you need to resolve manually.</p>
</li>
<li><p>Git creates a new merge commit that points to your "add_search" branch head and the main branch head (including Commit X).</p>
</li>
</ol>
<p><strong>Result:</strong> Your local "add_search" branch maintains its two commits but has a new merge commit on top that signifies the integration with the main branch (including Commit X). The commit history becomes slightly more complex with a merge point.</p>
<h2 id="heading-semantic-versioning">Semantic Versioning</h2>
<p>Semantic Versioning (<em>aka - SemVer</em>) is a versioning scheme used for software to communicate the nature and impact of changes in a project. It helps developers and users understand the compatibility and potential risks associated with upgrading to a new version. Here's a breakdown of the key aspects of SemVer:</p>
<ul>
<li><p><strong>Version format:</strong> SemVer uses a three-part version number format: <code>Major.Minor.Patch</code> (e.g., 2.1.4).</p>
<ul>
<li><p><strong>Major:</strong> Incremented for breaking changes (changes that cause existing code to stop working).</p>
</li>
<li><p><strong>Minor:</strong> Incremented for new features that maintain backward compatibility (existing code should still work).</p>
</li>
<li><p><strong>Patch:</strong> Incremented for bug fixes that maintain backward compatibility.</p>
</li>
</ul>
</li>
<li><p><strong>Public API:</strong> SemVer assumes there's a well-defined public API (application programming interface) for your software. This API defines how users interact with your software.</p>
</li>
<li><p><strong>Backward Compatibility:</strong> A core principle of SemVer is maintaining backward compatibility. This means that in most cases, users should be able to upgrade to a new version without having to modify their existing code.</p>
</li>
</ul>
<p>Here's a table summarizing the impact of changes on each version component:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Version Component</td><td>Increment When</td><td>Impact on Users</td></tr>
</thead>
<tbody>
<tr>
<td>Major</td><td>Backwards-incompatible changes</td><td>Users might need to modify their code</td></tr>
<tr>
<td>Minor</td><td>New features with backwards compatibility</td><td>Users can upgrade seamlessly</td></tr>
<tr>
<td>Patch</td><td>Bug fixes with backwards compatibility</td><td>Users can upgrade seamlessly</td></tr>
</tbody>
</table>
</div><p><strong>Benefits of using Semantic Versioning:</strong></p>
<ul>
<li><p><strong>Clear Communication:</strong> Provides a clear and concise way to communicate the nature and impact of changes in a version number.</p>
</li>
<li><p><strong>Backward Compatibility:</strong> Helps maintain backward compatibility, making it easier for users to upgrade without breaking their applications.</p>
</li>
<li><p><strong>Reduced Risk:</strong> Allows users to make informed decisions about upgrades based on version numbers and potential breaking changes.</p>
</li>
<li><p><strong>Version Dependency Management:</strong> Simplifies dependency management for projects that rely on other software components with their own versions.</p>
</li>
</ul>
<p>Overall, Semantic Versioning promotes a consistent and predictable approach to software versioning, fostering better communication and collaboration between developers and users.</p>
]]></content:encoded></item><item><title><![CDATA[Examination Preparation Materials - Chapter 05]]></title><description><![CDATA[Product Management & Project Management
Product Management: Focuses on the "what" and "why" of a product. They are responsible for the overall vision, strategy, and roadmap of a product throughout its lifecycle. This includes understanding customer n...]]></description><link>https://khalti.engineering/examination-preparation-materials-chapter-05</link><guid isPermaLink="true">https://khalti.engineering/examination-preparation-materials-chapter-05</guid><category><![CDATA[institute-of-engineering]]></category><category><![CDATA[applied-fintech-engineering]]></category><category><![CDATA[pulchowk-campus]]></category><category><![CDATA[fintech software development]]></category><category><![CDATA[project management]]></category><dc:creator><![CDATA[Dhruba Adhikari]]></dc:creator><pubDate>Thu, 28 Mar 2024 10:42:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/qWwpHwip31M/upload/ef8fa424824a3abbb8c0f8ed7cf917a4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-product-management-amp-project-management"><strong>Product Management &amp; Project Management</strong></h2>
<p><strong>Product Management:</strong> Focuses on the <strong>"what" and "why"</strong> of a product. They are responsible for the overall vision, strategy, and roadmap of a product throughout its lifecycle. This includes understanding customer needs, defining product requirements, and ensuring the product delivers value.</p>
<p><strong>Project Management:</strong> Focuses on the <strong>"how" and "when"</strong> of delivering specific tasks within a project. They oversee the execution of a project plan, manage resources, track progress, and ensure projects are completed on time and within budget.</p>
<p><strong>Analogy:</strong> Think of a product manager as the architect who designs the house (product) and the project manager as the foreman who oversees construction (project) following the architect's blueprint.</p>
<h2 id="heading-waterfall-model-and-agile-model-for-software-development"><strong>Waterfall Model and Agile Model for Software Development</strong></h2>
<p><strong>Waterfall Model:</strong> A traditional, sequential approach where each development phase (requirements gathering, design, development, testing, deployment) is completed in order before moving to the next. This method offers clear milestones and control but can be inflexible and slow to adapt to changing needs.</p>
<p><strong>Agile Model:</strong> An iterative and incremental approach to software development. Projects are broken down into smaller "sprints" with continuous feedback loops. This allows for faster delivery of working features and easier adaptation to changing requirements.</p>
<p><strong>Think of it this way:</strong> Waterfall is like building a house one floor at a time, needing a complete plan upfront. Agile is like building a house one room / floor at a time, adapting the plan as you go. In the Agile model, you can even start living to the floor that's already ready while the construction continues.</p>
<h2 id="heading-building-a-house-agile-vs-waterfall"><strong>Building a House: Agile vs. Waterfall</strong></h2>
<h3 id="heading-waterfall-approach-traditional-method"><strong>Waterfall Approach (Traditional Method):</strong></h3>
<p><strong>Imagine you have a detailed blueprint for your dream house.</strong> This blueprint outlines everything from the foundation to the roof, including materials, permits, and construction phases.</p>
<p><strong>Following the blueprint rigidly, you proceed sequentially:</strong></p>
<ul>
<li><p><strong>Phase 1: Foundation &amp; Framing:</strong> The foundation is poured, and the entire house frame is built based on the blueprint.</p>
</li>
<li><p><strong>Phase 2: Plumbing &amp; Electrical:</strong> With the frame complete, plumbers and electricians install all the necessary systems based on pre-defined locations in the blueprint.</p>
</li>
<li><p><strong>Phase 3: Walls &amp; Roof:</strong> Walls are built, and the roof is installed according to the blueprint.</p>
</li>
<li><p><strong>Phase 4: Interior Finishing:</strong> This involves everything from flooring and painting to installing cabinets and fixtures, all based on the specifications in the blueprint.</p>
</li>
</ul>
<p><strong>Pros:</strong></p>
<ul>
<li><p><strong>Clear Plan &amp; Milestones:</strong> You have a clear roadmap from start to finish with defined milestones at each phase.</p>
</li>
<li><p><strong>Cost &amp; Schedule Visibility:</strong> Easier to estimate final costs and project duration upfront due to a fixed plan.</p>
</li>
<li><p><strong>Reduced Risk of Major Changes:</strong> Difficult to make significant changes mid-construction, reducing overall complexity.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p><strong>Inflexible to Changes:</strong> New ideas or unforeseen problems can be expensive and time-consuming to accommodate once construction progresses.</p>
</li>
<li><p><strong>Limited Customer Input:</strong> Focuses on the initial plan with less room for customer feedback during construction.</p>
</li>
<li><p><strong>Potential for Delays:</strong> Delays in one phase can ripple through the entire project, affecting completion date and budget.</p>
</li>
</ul>
<h3 id="heading-agile-approach-incremental-method"><strong>Agile Approach (Incremental Method):</strong></h3>
<p><strong>Imagine building your house one room at a time.</strong> You start with a basic structure and then work on specific sections in short cycles called "sprints."</p>
<ul>
<li><p><strong>Each sprint has a clear objective:</strong> For example, building the kitchen in the first sprint, bathrooms in the second, and so on.</p>
</li>
<li><p><strong>After each sprint, the team evaluates progress and incorporates feedback from stakeholders (future residents!).</strong> This allows for adjustments to the plan based on new information or changing needs.</p>
</li>
<li><p><strong>The process is iterative:</strong> You learn and adapt as you go, potentially changing materials, layouts, or even adding features based on the evolving vision.</p>
</li>
</ul>
<p><strong>Pros:</strong></p>
<ul>
<li><p><strong>Fast Adaptability:</strong> Can readily incorporate changes and new ideas throughout the building process.</p>
</li>
<li><p><strong>Continuous Customer Input:</strong> Customers (future residents) can provide feedback and influence the final outcome.</p>
</li>
<li><p><strong>Reduced Risk of Big Mistakes:</strong> Errors are caught and addressed earlier, preventing them from becoming major issues later.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p><strong>Uncertain Final Cost &amp; Schedule:</strong> Difficult to predict the final cost and project duration due to the iterative nature.</p>
</li>
<li><p><strong>Requires Strong Communication:</strong> Frequent communication and collaboration are crucial between the team and stakeholders.</p>
</li>
<li><p><strong>Potential for Scope Creep:</strong> The project can potentially grow in scope if changes are not carefully managed.</p>
</li>
</ul>
<h2 id="heading-product-owner-and-scrum-master"><strong>Product Owner and Scrum Master</strong></h2>
<p>These roles are specific to the Agile Scrum framework:</p>
<p><strong>Product Owner:</strong> Represents the stakeholders and prioritizes the product backlog (list of features) based on business needs and customer value. They ensure the product backlog reflects the product vision and communicates requirements to the development team.</p>
<p><strong>Scrum Master:</strong> Acts as a coach and facilitator for the Scrum team. They ensure the team understands Agile principles, removes roadblocks, protects the team's time, and keeps the Scrum process running smoothly.</p>
<h2 id="heading-principles-from-the-agile-manifesto"><strong>Principles from the Agile Manifesto</strong></h2>
<p>(Reference : <a target="_blank" href="https://www.agilealliance.org/agile101/12-principles-behind-the-agile-manifesto/">https://www.agilealliance.org/agile101/12-principles-behind-the-agile-manifesto/</a>)</p>
<p>The Agile Manifesto outlines core values for software development:</p>
<ol>
<li><p><strong>Customer Satisfaction Through Early &amp; Continuous Delivery:</strong> The top priority is to deliver valuable software to customers early and often, fostering continuous feedback and improvement.</p>
</li>
<li><p><strong>Welcome Changing Requirements:</strong> Agile embraces changing requirements even late in development. These changes are seen as opportunities to improve the product based on new learnings.</p>
</li>
<li><p><strong>Deliver Working Software Frequently:</strong> Focus on delivering working software in short, regular intervals (weeks or months) to get user feedback quickly and adapt accordingly.</p>
</li>
<li><p><strong>Business People &amp; Developers Collaborate Daily:</strong> Close collaboration between business stakeholders and developers throughout the project ensures everyone is aligned on priorities and goals.</p>
</li>
<li><p><strong>Build Projects Around Motivated Individuals:</strong> Empower and trust motivated individuals by providing them with the environment and support they need to excel.</p>
</li>
<li><p><strong>Face-to-Face Conversation is Most Effective:</strong> The most efficient and effective communication for agile teams is through face-to-face conversation. This fosters clear understanding and reduces misunderstandings.</p>
</li>
<li><p><strong>Working Software is the Primary Measure of Progress:</strong> The primary measure of progress is the delivery of working software that provides value to customers.</p>
</li>
<li><p><strong>Sustainable Development Pace:</strong> Agile promotes a sustainable development pace that avoids developer burnout and ensures a constant, healthy development flow.</p>
</li>
<li><p><strong>Continuous Attention to Technical Excellence:</strong> Continuous attention to technical excellence and good design enhances agility by improving maintainability and adaptability of the software.</p>
</li>
<li><p><strong>Simplicity—the Art of Maximizing the Undone Work:</strong> Focus on simplicity by prioritizing the essential work and eliminating unnecessary complexity. This frees up time and resources for what truly matters.</p>
</li>
<li><p><strong>Self-Organizing Teams Deliver the Greatest Value:</strong> The best architecture, requirements, and designs emerge from self-organizing teams. These teams are empowered to make decisions and take ownership of their work.</p>
</li>
<li><p><strong>Regular Reflection on How to Become More Agile:</strong> Agile teams should regularly reflect on how to become more effective, continuously tuning their processes and behaviors to improve their agility.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Examination Preparation Materials - Chapter 04]]></title><description><![CDATA[Multi-Tenant Systems
Definition: A multi-tenant system is a software architecture where a single instance of an application serves multiple independent users or organizations (tenants). It's like an apartment building where tenants share the same inf...]]></description><link>https://khalti.engineering/examination-preparation-materials-chapter-04</link><guid isPermaLink="true">https://khalti.engineering/examination-preparation-materials-chapter-04</guid><category><![CDATA[python sample codes]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[applied-fintech-engineering]]></category><category><![CDATA[pulchowk-campus]]></category><category><![CDATA[Tribhuvan University]]></category><category><![CDATA[khalti]]></category><dc:creator><![CDATA[Dhruba Adhikari]]></dc:creator><pubDate>Wed, 13 Mar 2024 12:18:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/hoivM01c-vg/upload/f40e2a7e5f2d2ae72bcdb0da34077fbc.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-multi-tenant-systems"><strong>Multi-Tenant Systems</strong></h2>
<p><strong>Definition:</strong> A multi-tenant system is a software architecture where a single instance of an application serves multiple independent users or organizations (tenants). It's like an apartment building where tenants share the same infrastructure (building) but have private spaces (apartments) with their own data and configurations.</p>
<p><strong>Database Schema with Tenant Isolation</strong></p>
<p>Leverage a database schema designed to isolate tenant data. This can be achieved through:</p>
<ol>
<li><p>Tenant-specific columns or tables: Each tenant has its own data columns or tables, preventing data mixing.</p>
</li>
<li><p>Multi-tenancy frameworks: Frameworks like Django's Tenant model or Ruby on Rails' multi-tenancy plugins automate tenant isolation within the database schema.</p>
</li>
</ol>
<p><strong>Configuration Management</strong></p>
<p>Store tenant-specific configurations (settings, preferences) separately. This could involve:</p>
<ol>
<li><p>Configuration databases: Maintain a separate database or table for each tenant's configurations.</p>
</li>
<li><p>Key-value stores: Utilize key-value stores like Redis or AWS DynamoDB to store tenant configurations as key-value pairs.</p>
</li>
</ol>
<hr />
<h2 id="heading-design-patterns"><strong>Design Patterns</strong></h2>
<p>In the realm of software design, a design pattern is a <strong>well-established, proven solution</strong> that acts as a <strong>reusable template</strong> to tackle <strong>frequently encountered programming challenges</strong>. It's not a piece of code you directly copy and paste, but rather a <strong>conceptual blueprint</strong> that outlines the structure and relationships between classes or objects to achieve a specific functionality.</p>
<p>Think of it like a recipe in a cookbook. The recipe provides a general framework for creating a dish, but you can adjust the ingredients and quantities to suit your personal preferences. Similarly, a design pattern outlines the essential steps and components for solving a particular design problem, but you can adapt it to the specific context of your software application.</p>
<blockquote>
<p>If i have to say in one sentence - Design patterns provide predictability to the code segments. - Dhruba Adhikari, CTO (Khalti)</p>
</blockquote>
<h3 id="heading-singleton-pattern"><strong>Singleton Pattern</strong></h3>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Singleton</span>(<span class="hljs-params">object</span>):</span>
  _instance = <span class="hljs-literal">None</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__new__</span>(<span class="hljs-params">cls, *args, **kwargs</span>):</span>
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> cls._instance:
      cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
    <span class="hljs-keyword">return</span> cls._instance

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, data=None</span>):</span>
    <span class="hljs-comment"># Optionally, you can add initialization logic here</span>
    <span class="hljs-comment"># if data is not None:</span>
    <span class="hljs-comment">#   self.data = data</span>
    <span class="hljs-keyword">pass</span>

  <span class="hljs-comment"># Add your class methods here</span>

<span class="hljs-comment"># Usage example</span>
singleton_instance1 = Singleton()
singleton_instance2 = Singleton()

<span class="hljs-comment"># Both singleton_instance1 and singleton_instance2 will </span>
<span class="hljs-comment"># refer to the same object</span>

<span class="hljs-comment"># You can optionally add data to the Singleton instance </span>
<span class="hljs-comment"># during initialization</span>
<span class="hljs-comment"># singleton_instance3 = Singleton(data="Some data")</span>
</code></pre>
<ul>
<li><p>Ensures a class has only one instance and provides a global access point to it.</p>
</li>
<li><p>Use case: Managing a system-wide logger or configuration manager.</p>
</li>
</ul>
<h3 id="heading-factory-pattern"><strong>Factory Pattern</strong></h3>
<pre><code class="lang-python"><span class="hljs-comment"># Interface for the product being created</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Product</span>:</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">do_something</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-keyword">raise</span> NotImplementedError(<span class="hljs-string">"Subclasses must implement do_something"</span>)

<span class="hljs-comment"># Concrete product implementations</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductA</span>(<span class="hljs-params">Product</span>):</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">do_something</span>(<span class="hljs-params">self</span>):</span>
    print(<span class="hljs-string">"ProductA does something"</span>)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductB</span>(<span class="hljs-params">Product</span>):</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">do_something</span>(<span class="hljs-params">self</span>):</span>
    print(<span class="hljs-string">"ProductB does something"</span>)

<span class="hljs-comment"># Factory class to create products</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductFactory</span>:</span>
<span class="hljs-meta">  @staticmethod</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_product</span>(<span class="hljs-params">product_type</span>):</span>
    <span class="hljs-keyword">if</span> product_type == <span class="hljs-string">"A"</span>:
      <span class="hljs-keyword">return</span> ProductA()
    <span class="hljs-keyword">elif</span> product_type == <span class="hljs-string">"B"</span>:
      <span class="hljs-keyword">return</span> ProductB()
    <span class="hljs-keyword">else</span>:
      <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Invalid product type"</span>)

<span class="hljs-comment"># Usage example</span>
product = ProductFactory.create_product(<span class="hljs-string">"A"</span>)
product.do_something()  <span class="hljs-comment"># Output: ProductA does something</span>
</code></pre>
<ul>
<li><p>Creates objects without specifying the exact class to be instantiated.</p>
</li>
<li><p>Use case: Generating different types of financial transactions based on user input.</p>
</li>
</ul>
<h3 id="heading-observer-pattern"><strong>Observer Pattern</strong></h3>
<pre><code class="lang-python"><span class="hljs-comment"># Interface for the subject (observable)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Subject</span>:</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
    self._observers = []

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">register_observer</span>(<span class="hljs-params">self, observer</span>):</span>
    self._observers.append(observer)

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">unregister_observer</span>(<span class="hljs-params">self, observer</span>):</span>
    self._observers.remove(observer)

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">notify_observers</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-keyword">for</span> observer <span class="hljs-keyword">in</span> self._observers:
      observer.update(self)

<span class="hljs-comment"># Interface for the observer</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Observer</span>:</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update</span>(<span class="hljs-params">self, subject</span>):</span>
    <span class="hljs-keyword">raise</span> NotImplementedError(<span class="hljs-string">"Subclasses must implement update"</span>)

<span class="hljs-comment"># Concrete subject implementation</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConcreteSubject</span>(<span class="hljs-params">Subject</span>):</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">do_something</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-comment"># ... change state ...</span>
    self.notify_observers()

<span class="hljs-comment"># Concrete observer implementation</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConcreteObserver</span>(<span class="hljs-params">Observer</span>):</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update</span>(<span class="hljs-params">self, subject</span>):</span>
    print(<span class="hljs-string">f"Observer notified: <span class="hljs-subst">{subject.__class__.__name__}</span>"</span>)

<span class="hljs-comment"># Usage example</span>
subject = ConcreteSubject()
observer1 = ConcreteObserver()
observer2 = ConcreteObserver()

subject.register_observer(observer1)
subject.register_observer(observer2)

subject.do_something()  <span class="hljs-comment"># Output: Observer notified: ConcreteSubject</span>
</code></pre>
<ul>
<li><p>Defines a one-to-many dependency between objects, where changes to one object (subject) notify and update all dependent objects (observers).</p>
</li>
<li><p>Use case: Alerting fraud detection modules or notifying interested parties about account activity.</p>
</li>
<li><p>Django Signals are implementation of the Observer pattern.</p>
</li>
</ul>
<h3 id="heading-adapter-pattern"><strong>Adapter Pattern</strong></h3>
<p><strong>Scenario:</strong> You have a library that can calculate the area of different shapes (square, circle) but expects specific functions for each shape. You want to use a different library that calculates area using a single <code>calculate_area</code> function with a shape object as input.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Existing library functions (incompatible interfaces)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculate_square_area</span>(<span class="hljs-params">side_length</span>):</span>
  <span class="hljs-keyword">return</span> side_length * side_length

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculate_circle_area</span>(<span class="hljs-params">radius</span>):</span>
  <span class="hljs-keyword">return</span> <span class="hljs-number">3.14</span> * radius * radius

<span class="hljs-comment"># Shape class for the new library (compatible interface)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span>:</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, type</span>):</span>
    self.type = type

<span class="hljs-comment"># Adapter class (bridge between interfaces)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ShapeAreaAdapter</span>(<span class="hljs-params">Shape</span>):</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, type, side_length=None, radius=None</span>):</span>
    super().__init__(type)
    self.side_length = side_length
    self.radius = radius

  <span class="hljs-comment"># Translate request to compatible format</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculate_area</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-keyword">if</span> self.type == <span class="hljs-string">"square"</span>:
      <span class="hljs-keyword">return</span> calculate_square_area(self.side_length)
    <span class="hljs-keyword">elif</span> self.type == <span class="hljs-string">"circle"</span>:
      <span class="hljs-keyword">return</span> calculate_circle_area(self.radius)
    <span class="hljs-keyword">else</span>:
      <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Unsupported shape type"</span>)

<span class="hljs-comment"># Usage example</span>
square_adapter = ShapeAreaAdapter(<span class="hljs-string">"square"</span>, side_length=<span class="hljs-number">5</span>)
circle_adapter = ShapeAreaAdapter(<span class="hljs-string">"circle"</span>, radius=<span class="hljs-number">3</span>)

square_area = square_adapter.calculate_area()
circle_area = circle_adapter.calculate_area()

print(<span class="hljs-string">f"Square area: <span class="hljs-subst">{square_area}</span>"</span>)  <span class="hljs-comment"># Output: Square area: 25</span>
print(<span class="hljs-string">f"Circle area: <span class="hljs-subst">{circle_area}</span>"</span>)  <span class="hljs-comment"># Output: Circle area: 28.26</span>
</code></pre>
<ul>
<li><p>Allows incompatible interfaces to work together by wrapping an existing class with an interface the client expects.</p>
</li>
<li><p>Use case: Integrating with legacy financial systems that use different communication protocols.</p>
</li>
<li><p><strong>Imagine you have a music player that only plays MP3 files, but you want to play a WAV file.</strong> The adapter pattern is like using a converter to change the WAV file into an MP3 format that the player can understand.</p>
</li>
</ul>
<hr />
<h2 id="heading-encryption-understanding">Encryption Understanding</h2>
<p>Encryption plays a crucial role in safeguarding sensitive information in fintech applications. Understanding the two main types of encryption, symmetric and asymmetric, is essential for making informed decisions about data security.</p>
<h3 id="heading-symmetric-encryption"><strong>Symmetric Encryption</strong></h3>
<p>Symmetric encryption uses a single, shared secret key for both encryption and decryption. It's like a key to a locked door; the same key unlocks and locks the door.</p>
<p><strong>Characteristics:</strong></p>
<ul>
<li><p><strong>Fast and Efficient:</strong> Symmetric encryption is faster than asymmetric encryption due to simpler algorithms.</p>
</li>
<li><p><strong>Key Management:</strong> The biggest challenge is securely managing the shared secret key. Any unauthorized access to the key compromises all encrypted data.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p><strong>Securing Data at Rest:</strong> Symmetric encryption is ideal for encrypting data stored on databases or local devices, ensuring confidentiality.</p>
</li>
<li><p><strong>Secure Communication Channels:</strong> HTTPS (Secure Hypertext Transfer Protocol) often utilizes symmetric encryption within a secure socket layer (SSL/TLS) for secure communication between a web server and browser.</p>
</li>
<li><p><strong>Data Encryption in Transit:</strong> Symmetric encryption can be used to encrypt data during transmission between authorized parties, like secure file transfer protocols (SFTP).</p>
</li>
</ul>
<h3 id="heading-asymmetric-encryption"><strong>Asymmetric Encryption</strong></h3>
<p>Asymmetric encryption employs a pair of mathematically linked keys: a public key and a private key. The public key is widely distributed, while the private key is kept secret. Data encrypted with the public key can only be decrypted with the corresponding private key.</p>
<p><strong>Characteristics:</strong></p>
<ul>
<li><p><strong>Security through Key Separation:</strong> Public and private keys being separate strengthens security. Even if the public key is compromised, attackers cannot decrypt data without the private key.</p>
</li>
<li><p><strong>Slower Performance:</strong> Asymmetric encryption involves complex algorithms, making it slower than symmetric encryption.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p><strong>Digital Signatures:</strong> Public-key cryptography forms the basis for digital signatures. A document can be signed with a private key, and anyone can verify its authenticity using the corresponding public key. This ensures data integrity and non-repudiation.</p>
</li>
<li><p><strong>Secure Key Exchange:</strong> Sending a symmetric key securely can be done using asymmetric encryption. The recipient uses their private key to decrypt the symmetric key, which is then used for bulk data encryption/decryption.</p>
</li>
<li><p><strong>Secure Logins:</strong> Some secure login systems leverage asymmetric encryption. Passwords are not stored directly; instead, they are used to generate a temporary key that unlocks a session key for secure communication.</p>
</li>
</ul>
<p><strong>Combined Use Case:</strong></p>
<p>A common scenario in fintech applications combines both symmetric and asymmetric encryption:</p>
<ol>
<li><p>A mobile banking app needs to securely transmit user credentials (e.g., username, password) to the bank server.</p>
</li>
<li><p>The app uses <strong>symmetric</strong> encryption (e.g., AES) to encrypt the credentials using a randomly generated session key.</p>
</li>
<li><p>The app establishes a secure connection with the server using HTTPS (which uses an <strong>asymmetric</strong> key exchange between the server and user's device).</p>
</li>
<li><p>The app sends the encrypted session key (using the server's public key) and the encrypted credentials to the server.</p>
</li>
<li><p>The server decrypts the session key using its private key.</p>
</li>
<li><p>The server uses the now-known session key to decrypt the user credentials using symmetric decryption.</p>
</li>
</ol>
<p>This approach provides a layered security mechanism:</p>
<ul>
<li><p>Symmetric encryption ensures fast and efficient encryption of sensitive data in transit.</p>
</li>
<li><p>Asymmetric encryption facilitates secure key exchange without revealing the private key, strengthening overall security.</p>
</li>
</ul>
<h2 id="heading-scaling-applications">Scaling applications</h2>
<p>When your fintech application experiences increased user traffic or data processing demands, you'll need to consider scaling strategies to maintain performance and functionality. Here's a breakdown of two common approaches:</p>
<h3 id="heading-horizontal-scaling-scale-out"><strong>Horizontal Scaling (Scale Out)</strong></h3>
<p>This approach involves adding <strong>more machines (servers)</strong> to your existing infrastructure. You distribute the workload across these additional servers, achieving scalability by leveraging parallel processing power.</p>
<p><em>Analogy : Add one more Boiler to make more momos</em></p>
<p><strong>Benefits</strong></p>
<ul>
<li><p><strong>Increased Capacity:</strong> More servers provide more processing power, memory, and storage, allowing you to handle higher loads efficiently.</p>
</li>
<li><p><strong>Improved Fault Tolerance:</strong> If one server fails, the others can continue processing requests, enhancing system availability.</p>
</li>
<li><p><strong>Flexibility and Cost-Effectiveness:</strong> You can add or remove servers as needed, offering better resource utilization and potentially lower costs compared to high-end hardware upgrades.</p>
</li>
</ul>
<p><strong>Challenges</strong></p>
<ul>
<li><p><strong>Complexity:</strong> Managing multiple servers and ensuring workload distribution can become complex as the infrastructure scales.</p>
</li>
<li><p><strong>Development Considerations:</strong> Your application needs to be designed to work efficiently in a distributed environment.</p>
</li>
</ul>
<h3 id="heading-vertical-scaling-scale-up"><strong>Vertical Scaling (Scale Up)</strong></h3>
<p>This approach focuses on upgrading the existing hardware resources of your server(s). You might add more CPU cores, RAM, or storage to enhance its processing power and capacity.</p>
<p><em>Analogy : Bring a bigger Boiler to make more momos.</em></p>
<p><strong>Benefits:</strong></p>
<ul>
<li><p><strong>Simpler Management:</strong> Less complex than managing multiple servers, especially for smaller applications.</p>
</li>
<li><p><strong>Faster Implementation:</strong> Upgrading hardware can be quicker than setting up and configuring a distributed system.</p>
</li>
</ul>
<p><strong>Challenges:</strong></p>
<ul>
<li><p><strong>Limited Scalability:</strong> There's eventually a physical limit to how much you can upgrade a single server.</p>
</li>
<li><p><strong>Single Point of Failure:</strong> If the upgraded server fails, the entire system goes down.</p>
</li>
<li><p><strong>Potentially Higher Cost:</strong> Upgrading high-end hardware can be more expensive than adding commodity servers in a horizontal scaling approach.</p>
</li>
</ul>
<p><strong>Choosing the Right Strategy:</strong></p>
<p>The optimal scaling strategy depends on your specific needs and application characteristics. Horizontal scaling is generally preferred for large-scale, high-traffic web applications where flexibility and fault tolerance are crucial. Vertical scaling might be suitable for smaller applications with predictable workloads where simplicity and rapid deployment are priorities.</p>
<h3 id="heading-momo-scaling"><strong>Momo Scaling</strong></h3>
<ul>
<li><p><strong>High Demand, Multiple Locations:</strong> If customer demand is high and you have the opportunity to expand geographically, horizontal scaling with new branches might be a good choice.</p>
</li>
<li><p><strong>Limited Space, Growing Demand:</strong> If space limitations restrict new branches, consider vertical scaling by upgrading your kitchen equipment and processes to increase momo production capacity.</p>
</li>
</ul>
<h2 id="heading-greenfield-vs-brownfield-strategies-building-software"><strong>Greenfield vs. Brownfield Strategies: Building Software</strong></h2>
<h3 id="heading-greenfield-strategy"><strong>Greenfield Strategy</strong></h3>
<p>This approach involves starting fresh with a new application from scratch. You have the freedom to choose the latest technologies, frameworks, and architecture without being constrained by existing legacy systems.</p>
<p><strong>Benefits:</strong></p>
<ul>
<li><p><strong>Modern and Efficient Technologies:</strong> You can leverage the latest advancements in software development to build a high-performance and scalable application.</p>
</li>
<li><p><strong>Flexibility and Agility:</strong> The development process is less restricted by existing codebase limitations, allowing for faster iteration and adaptation.</p>
</li>
</ul>
<p><strong>Challenges:</strong></p>
<ul>
<li><p><strong>Increased Development Time and Cost:</strong> Building a new application from scratch requires significant upfront investment in design, development, and testing.</p>
</li>
<li><p><strong>Integration with Existing Systems:</strong> If you need to integrate with existing legacy systems, additional effort might be required.</p>
</li>
</ul>
<h3 id="heading-brownfield-strategy"><strong>Brownfield Strategy</strong></h3>
<p>This approach focuses on evolving and improving an existing application. You can gradually modernize, refactor, and enhance the existing codebase while keeping the core functionality intact.</p>
<p><strong>Benefits:</strong></p>
<ul>
<li><p><strong>Lower Development Cost:</strong> Leveraging existing code can save time and resources compared to a complete rewrite.</p>
</li>
<li><p><strong>Reduced Risk:</strong> Modifying existing code is generally less risky than building a new system from scratch.</p>
</li>
</ul>
<p><strong>Challenges:</strong></p>
<ul>
<li><p><strong>Technical Debt:</strong> Legacy code might have inefficiencies or outdated technologies, making modifications challenging.</p>
</li>
<li><p><strong>Limited Flexibility:</strong> Existing code structure might limit the adoption of new features and functionalities.</p>
</li>
</ul>
<p><strong>Choosing the Right Strategy:</strong></p>
<p>The choice between Greenfield and Brownfield strategies depends on various factors like the state of your existing application, budget, resource availability, and desired speed of change.</p>
<p>For completely new applications or outdated, inflexible legacy systems, a Greenfield approach might be more suitable. For gradually modernizing and enhancing existing functionality, a Brownfield strategy might be preferred. In some cases, a hybrid approach combining elements of both strategies can be effective.</p>
<p><strong>Analogy :</strong></p>
<ol>
<li><p><strong>Greenfield</strong> : You build a new house because you wanted to upgrade your lifestyle</p>
</li>
<li><p><strong>Brownfield</strong> : You work on floor by floor remodeling, while relocating to different floors as the work progresses.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Examination Preparation Materials - Chapter 03]]></title><description><![CDATA[What is a payment rail application? Give an example of how a payment rail application integrates into some software.
A payment rail application is a platform or system that facilitates the movement of funds between parties in a financial transaction....]]></description><link>https://khalti.engineering/examination-preparation-materials-chapter-03</link><guid isPermaLink="true">https://khalti.engineering/examination-preparation-materials-chapter-03</guid><category><![CDATA[applied-fintech-engineering]]></category><category><![CDATA[examination preparation materials]]></category><category><![CDATA[ioe-elective]]></category><category><![CDATA[Tribhuvan University]]></category><dc:creator><![CDATA[Dhruba Adhikari]]></dc:creator><pubDate>Wed, 13 Mar 2024 10:30:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1710330384757/0464ccb0-ed00-4d7f-bca6-f0afe605be86.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-is-a-payment-rail-application-give-an-example-of-how-a-payment-rail-application-integrates-into-some-software"><strong>What is a payment rail application? Give an example of how a payment rail application integrates into some software.</strong></h3>
<p>A payment rail application is a platform or system that facilitates the movement of funds between parties in a financial transaction. It acts as an intermediary, providing the infrastructure and protocols necessary for transferring money securely and efficiently. An example of a payment rail application is the Automated Clearing House (ACH) network in the United States, which enables electronic bank-to-bank transfers.</p>
<p>Integration of a payment rail application into software typically involves using Application Programming Interfaces (APIs) provided by the payment rail service. For instance, a software application may utilize the ACH API to initiate fund transfers from customers' bank accounts to merchants. The software would communicate with the payment rail application through the API, submitting transaction details and receiving confirmation once the transfer is completed. This integration allows businesses to offer seamless payment options to their customers while leveraging the capabilities of established payment infrastructure.</p>
<ol>
<li><p><strong>NCHL-IPS (National Payments Interface - Interbank Payment System)</strong>: NCHL-IPS is a real-time gross settlement system operated by the Nepal Clearing House Ltd. (NCHL). It facilitates interbank fund transfers in real-time, enabling individuals and businesses to make immediate payments between different banks in Nepal.</p>
</li>
<li><p><strong>NCHL-ECC (National Payments Interface - Electronic Cheque Clearing)</strong>: NCHL-ECC is an electronic cheque clearing system introduced by NCHL. It allows banks to exchange digital images of cheques electronically, speeding up the cheque clearing process and reducing the time required for cheque settlement.</p>
</li>
<li><p><strong>ConnectIPS</strong>: ConnectIPS is an online payment system developed by NCHL that enables users to initiate various types of electronic payments, including fund transfers, bill payments, and online purchases. It allows users to link their bank accounts from participating banks and conduct transactions conveniently through a single platform.</p>
</li>
<li><p><strong>RTGS (Real-Time Gross Settlement)</strong>: Some banks in Nepal offer RTGS services, allowing customers to initiate high-value, time-critical payments in real-time. RTGS enables immediate settlement of transactions, making it suitable for large interbank transfers and corporate payments that require instant processing.</p>
</li>
<li><p><strong>UPI (Unified Payments Interface)</strong>: UPI is a real-time payment system developed by the National Payments Corporation of India (NPCI). It allows users to link their bank accounts to a mobile app and make instant payments to individuals or merchants using a Virtual Payment Address (VPA) or account number with IFSC code.</p>
</li>
<li><p><strong>AEPS (Aadhaar Enabled Payment System)</strong>: AEPS is a payment system that allows customers to perform banking transactions using their Aadhaar number and biometric authentication at micro-ATMs. It enables financial inclusion by providing basic banking services to individuals in remote areas without access to traditional banking infrastructure.</p>
</li>
<li><p><strong>Bharat Bill Payment System (BBPS)</strong>: BBPS is an integrated bill payment platform that allows customers to pay bills, such as electricity, water, gas, and DTH, through a single interface. It provides interoperable and accessible bill payment services across various biller categories and payment channels.</p>
</li>
</ol>
<h3 id="heading-define-regtech-with-some-examples"><strong>Define RegTech with some examples</strong></h3>
<p>RegTech, short for Regulatory Technology, refers to the use of technology to streamline regulatory compliance processes within the financial industry. It encompasses various tools and solutions designed to help financial institutions comply with regulations more efficiently and cost-effectively. Examples of RegTech solutions include:</p>
<ul>
<li><p><strong>Compliance Monitoring Systems</strong>: Software platforms that automate the monitoring of regulatory requirements and alert financial institutions to any violations or discrepancies.</p>
</li>
<li><p><strong>Know Your Customer (KYC) Solutions</strong>: AI-powered tools that assist in verifying the identity of customers and performing due diligence checks to comply with anti-money laundering (AML) regulations.</p>
</li>
<li><p><strong>Transaction Surveillance Software</strong>: Systems that analyze financial transactions in real-time to detect suspicious activities and ensure compliance with regulatory standards.</p>
</li>
<li><p><strong>Regulatory Reporting Tools</strong>: Applications that simplify the process of preparing and submitting regulatory reports to governing authorities, reducing manual effort and improving accuracy.</p>
</li>
</ul>
<h3 id="heading-why-is-cryptocurrency-regarded-as-anonymous-provide-3-reasons-and-explain-them"><strong>Why is cryptocurrency regarded as anonymous? Provide 3 reasons and explain them</strong></h3>
<p>Cryptocurrency is often considered anonymous due to the following reasons:</p>
<ul>
<li><p><strong>Pseudonymous Nature</strong>: Cryptocurrency transactions are recorded on a public ledger (blockchain) using alphanumeric addresses instead of personal information. While these addresses do not directly reveal the identity of users, they are pseudonymous, meaning that transactions can be traced back to specific addresses.</p>
</li>
<li><p><strong>Decentralization</strong>: Cryptocurrencies operate on decentralized networks, where transactions are validated and recorded by multiple participants (nodes) rather than a central authority. This decentralized structure makes it challenging to link transactions to individuals without additional information.</p>
</li>
<li><p><strong>Privacy Features</strong>: Some cryptocurrencies, such as Monero and Zcash, incorporate privacy-enhancing features like stealth addresses and zero-knowledge proofs. These features obscure transaction details, making it more difficult to trace the flow of funds and identify users.</p>
</li>
</ul>
<p>However, it's essential to note that while cryptocurrency transactions offer a degree of privacy, they are not entirely anonymous. With the right tools and techniques, transactions can be analyzed and traced back to their originators, particularly in cases where users interact with regulated exchanges or platforms that require identity verification.</p>
<h3 id="heading-explain-3-fintech-application-areas-with-a-short-explanation-for-each"><strong>Explain 3 Fintech application areas with a short explanation for each</strong></h3>
<ol>
<li><p><strong>Payment Processing</strong>: Fintech companies offer payment processing solutions that enable businesses to accept electronic payments from customers, including credit/debit cards, mobile wallets, and online transfers. These solutions streamline transactions, enhance security, and provide valuable data insights for businesses.</p>
</li>
<li><p><strong>Digital Banking</strong>: Digital banking platforms provide customers with convenient access to banking services, such as account management, money transfers, bill payments, and budgeting tools, through web and mobile applications. Digital banks often operate without physical branches, offering cost-effective and accessible banking solutions.</p>
</li>
<li><p><strong>Robo-Advisory Services</strong>: Fintech firms leverage algorithms and automation to offer robo-advisory services for investment management and financial planning. These platforms analyze user preferences, risk tolerance, and financial goals to provide personalized investment advice and manage portfolios efficiently, often at lower fees than traditional financial advisors.</p>
</li>
</ol>
<h3 id="heading-what-is-fintech-as-a-service-explain-with-an-example"><strong>What is Fintech as a Service? Explain with an example</strong></h3>
<p>Fintech as a Service (FaaS) refers to the provision of fintech-related functionalities and services through Application Programming Interfaces (APIs) or cloud-based platforms, allowing businesses to integrate fintech capabilities into their products and services seamlessly.</p>
<p>For example, Stripe offers a suite of FaaS solutions for payment processing, fraud prevention, and subscription management. Businesses can integrate Stripe's APIs into their websites or applications to accept payments securely, automate recurring billing, and mitigate fraud risks without developing these capabilities in-house. FaaS enables businesses to leverage fintech expertise and infrastructure, accelerating innovation and improving the overall customer experience.</p>
<p>Some other examples are</p>
<ol>
<li><p><strong>APIs for Financial Data</strong>: Fintech firms offer APIs for accessing financial data, such as account balances, transaction history, and credit scores, from banks and financial institutions. Businesses, including fintech startups and traditional financial institutions, can use these APIs to enhance their products and services with personalized financial insights and recommendations.</p>
</li>
<li><p><strong>Payment Gateway Services</strong>: Fintech companies offer payment gateway APIs that allow businesses to accept online payments securely through their websites or mobile applications. These APIs handle transaction processing, encryption, and security protocols, enabling businesses to offer convenient payment options to their customers.</p>
</li>
<li><p><strong>Digital Lending Platforms</strong>: Fintech firms offer APIs and white-label lending platforms that enable banks, non-banking financial companies (NBFCs), and other financial institutions to offer digital lending products and services. These platforms facilitate loan origination, underwriting, disbursement, and collections, streamlining the lending process for businesses and consumers.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Examination Preparation Materials - Chapter 02]]></title><description><![CDATA[Sessions and Settlements in the Financial Ecosystem:
Sessions: In the financial ecosystem, sessions refer to the period during which financial transactions or activities are conducted. For example, a trading session in the stock market refers to the ...]]></description><link>https://khalti.engineering/examination-preparation-materials-chapter-02</link><guid isPermaLink="true">https://khalti.engineering/examination-preparation-materials-chapter-02</guid><category><![CDATA[ioe-elective]]></category><category><![CDATA[examination preparation materials]]></category><category><![CDATA[applied-fintech-engineering]]></category><dc:creator><![CDATA[Dhruba Adhikari]]></dc:creator><pubDate>Wed, 13 Mar 2024 10:22:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/xG8IQMqMITM/upload/a871f8087de16dfd70dbf0c439db7bed.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-sessions-and-settlements-in-the-financial-ecosystem"><strong>Sessions and Settlements in the Financial Ecosystem</strong>:</h3>
<p><strong>Sessions</strong>: In the financial ecosystem, sessions refer to the period during which financial transactions or activities are conducted. For example, a trading session in the stock market refers to the time when trading occurs, typically during specific hours of the day.</p>
<p>It can also be a window of time (eg. 10 AM to 1PM), which can later be accumulated, processed to perform transaction reconciliations, fee and commission calculations etc.</p>
<p><strong>Settlements</strong>: Settlements involve the process of transferring funds or securities to complete a financial transaction. It includes the reconciliation of transactions, confirmation of payment, and transfer of ownership or funds between parties. Settlements ensure that all parties involved in a transaction fulfill their obligations and that the transaction is finalized. Disbursement is a movement of fund. Settlement is everything required to be done before deciding the disbursement, and then running the disbursement.</p>
<h3 id="heading-four-party-model-in-fintech-ecosystem"><strong>Four Party Model in Fintech Ecosystem</strong>:</h3>
<p>The four-party model, also known as the four-corner model, is a common framework in the payment card industry that involves four key entities or parties collaborating to facilitate electronic payments. These parties include:</p>
<ol>
<li><p><strong>Cardholder</strong>: The individual or entity who owns and uses the payment card (e.g., credit card, debit card) to make purchases or transactions. The cardholder is typically the customer or consumer.</p>
</li>
<li><p><strong>Merchant</strong>: The business or entity that sells goods or services and accepts payment cards as a form of payment. Merchants require payment processing services to authorize and process card transactions.</p>
</li>
<li><p><strong>Acquirer (Merchant Bank)</strong>: The financial institution or bank that establishes and maintains relationships with merchants to enable them to accept payment cards. Acquirers provide merchants with the necessary equipment, software, and services for processing card transactions. They also settle funds from card transactions into the merchant's bank account.</p>
</li>
<li><p><strong>Issuer (Card Issuing Bank)</strong>: The financial institution or bank that issues payment cards to cardholders. Issuers are responsible for managing cardholder accounts, issuing cards, setting credit limits, processing transactions, and providing customer support to cardholders.</p>
</li>
</ol>
<p>In the four-party model, transactions involve interactions between these four key entities:</p>
<ul>
<li><p><strong>Authorization</strong>: When a cardholder makes a purchase at a merchant, the merchant sends the transaction details to the acquirer for authorization. The acquirer forwards the transaction to the issuer, which approves or declines the transaction based on the cardholder's account status and available funds.</p>
</li>
<li><p><strong>Clearing</strong>: After authorization, the transaction data is transmitted from the merchant's acquirer to the card network (e.g., Visa, Mastercard), which facilitates the clearing process. The card network routes the transaction data to the issuer for payment settlement.</p>
</li>
<li><p><strong>Settlement</strong>: The issuer transfers funds to the acquirer for the authorized transactions, and the acquirer deposits the funds into the merchant's bank account. Settlement typically occurs within a specified time frame, such as one to two business days after the transaction.</p>
</li>
</ul>
<p>The four-party model provides a standardized framework for processing card transactions, ensuring interoperability and cooperation among card networks, issuers, acquirers, and merchants in the payment ecosystem.</p>
<h3 id="heading-tokenization-in-the-fintech-ecosystem"><strong>Tokenization in the Fintech Ecosystem</strong>:</h3>
<p><strong>Tokenization</strong> is the process of replacing sensitive data, such as credit card numbers, with unique tokens that have no intrinsic value and are meaningless outside of the system that generated them. These tokens are used to represent the original data securely.</p>
<p><strong>Example</strong>: In a mobile payment app, when a user adds their credit card to make purchases, the app may tokenize the card number. Instead of storing the actual card number, the app generates a token linked to that card. When the user makes a payment, the token is sent to the payment processor instead of the card number, enhancing security by reducing the risk of exposing sensitive data in transit.</p>
<p>The payment processor or processing application like mobile wallets can reuse the token for future usage if required.</p>
<h3 id="heading-mdr-merchant-discount-rate-and-msf-merchant-service-fee"><strong>MDR (Merchant Discount Rate) and MSF (Merchant Service Fee)</strong>:</h3>
<p><strong>MDR (Merchant Discount Rate)</strong>: MDR is the <strong>fee charged by a payment acquirer</strong> to a merchant for processing debit and credit card transactions. It is usually a percentage of the transaction amount and covers the costs associated with processing payments, including interchange fees and network fees.</p>
<p><strong>MSF (Merchant Service Fee)</strong>: MSF is similar to MDR and represents the <strong>fee charged by payment processors to merchants</strong> for processing card transactions. It may include other fees in addition to the interchange fees, such as gateway fees and assessment fees.</p>
<h3 id="heading-idempotency-in-payment"><strong>Idempotency in Payment</strong>:</h3>
<p>Idempotency ensures that performing the same operation multiple times has the same effect as performing it once. In the context of payments, idempotency ensures that duplicate requests for the same transaction do not result in duplicate charges or actions.</p>
<p><strong>Example</strong>: Suppose a customer submits a payment request to purchase a product online. Due to network issues or timeouts, the customer's device doesn't receive an immediate response confirming the payment. As a result, the customer resubmits the payment request. If the system is designed to be idempotent, it will recognize that the second payment request is a duplicate and will not process it again, preventing the customer from being charged multiple times for the same transaction.</p>
]]></content:encoded></item><item><title><![CDATA[Examination Preparation Materials  - Chapter 01]]></title><description><![CDATA[Model Questions References for Examination Preparation
Difference between PSO and PSP, with Examples in Nepal
A Payment Service Operator (PSO) typically operates payment systems and infrastructures, while a Payment Service Provider (PSP) offers payme...]]></description><link>https://khalti.engineering/examination-preparation-materials-chapter-01</link><guid isPermaLink="true">https://khalti.engineering/examination-preparation-materials-chapter-01</guid><category><![CDATA[examination preparation materials]]></category><category><![CDATA[applied-fintech-engineering]]></category><dc:creator><![CDATA[Dhruba Adhikari]]></dc:creator><pubDate>Wed, 13 Mar 2024 10:11:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/PC91Jm1DlWA/upload/cc71d8c6783df19389cb7ae479e2a261.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Model Questions References for Examination Preparation</p>
<h3 id="heading-difference-between-pso-and-psp-with-examples-in-nepal"><strong>Difference between PSO and PSP, with Examples in Nepal</strong></h3>
<p>A Payment Service Operator (PSO) typically operates payment systems and infrastructures, while a Payment Service Provider (PSP) offers payment processing services to merchants and consumers. PSP has users and PSO has partners and associates in their network.</p>
<p>In Nepal, Nepal Clearing House Limited (NCHL) is a PSO responsible for operating national payment systems like NCHL-ECC and connectIPS.</p>
<p>Khalti is a PSP in Nepal, providing payment processing services for online and offline transactions. NCHL is defined as a PSO because it operates payment systems, whereas Khalti is a PSP because it provides payment processing services to merchants and consumers.</p>
<h3 id="heading-neo-bank-vs-traditional-bank"><strong>Neo-Bank vs. Traditional Bank</strong></h3>
<p>A Neo-Bank is a fully digital and branchless financial institution that offers banking services exclusively through digital channels, often without physical branches. Unlike traditional banks, Neo-Banks have lower overhead costs, offer innovative digital features, and can cater to underserved populations. Traditional banks, on the other hand, typically have physical branches and offer a broader range of financial products and services. Neo-Banks leverage technology to provide convenient, efficient, and cost-effective banking solutions to customers.</p>
<h3 id="heading-virtual-private-address-vpa-and-upi-in-india">Virtual Private Address (VPA) and UPI in India</h3>
<p>A Virtual Private Address (VPA) is a unique identifier linked to a user's bank account, used for making and receiving payments through the Unified Payments Interface (UPI) in India. With UPI, users can create VPAs, such as "example@bankname," which eliminates the need to share sensitive bank account details for transactions. For example, a user can use their VPA to request funds from another user or pay for goods and services online. VPAs standardize the payment ecosystem by providing a secure and user-friendly way to transact without exposing sensitive information.</p>
<h3 id="heading-tlv">TLV</h3>
<p>TLV stands for "Tag-Length-Value" and is a common format used to encode data in many communication protocols and data storage systems. In TLV format, each data element consists of three parts:</p>
<ol>
<li><p><strong>Tag</strong>: Identifies the type or purpose of the data element.</p>
</li>
<li><p><strong>Length</strong>: Specifies the length of the value field in bytes.</p>
</li>
<li><p><strong>Value</strong>: Contains the actual data associated with the tag.</p>
</li>
</ol>
<p>Here's a simple example of TLV format:</p>
<pre><code class="lang-plaintext">Tag (1 byte) | Length (1 byte) | Value (variable length)
</code></pre>
<p>Let's construct a TLV scheme for representing basic information about a person:</p>
<ul>
<li><p><strong>Tag 1 (Name)</strong>: Tag value = 0x01</p>
<ul>
<li><p>Length: Variable (depends on the length of the name)</p>
</li>
<li><p>Value: ASCII representation of the person's name</p>
</li>
</ul>
</li>
<li><p><strong>Tag 2 (Age)</strong>: Tag value = 0x02</p>
<ul>
<li><p>Length: 2 Characters</p>
<p>  Value: Numeric representation of the person's age in XX format</p>
</li>
</ul>
</li>
<li><p><strong>Tag 3 (Address)</strong>: Tag value = 0x03</p>
<ul>
<li><p>Length: Variable (depends on the length of the address)</p>
</li>
<li><p>Value: ASCII representation of the person's address</p>
</li>
</ul>
</li>
</ul>
<p>Example TLV-encoded data:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">Tag:</span> <span class="hljs-number">0x01</span> <span class="hljs-string">(Name)</span>
<span class="hljs-attr">Length:</span> <span class="hljs-number">7</span> <span class="hljs-string">bytes</span>
<span class="hljs-attr">Value:</span> <span class="hljs-string">Alice</span>

<span class="hljs-attr">Tag:</span> <span class="hljs-number">0x02</span> <span class="hljs-string">(Age)</span>
<span class="hljs-attr">Length:</span> <span class="hljs-number">2</span> <span class="hljs-string">Chars</span>
<span class="hljs-attr">Value:</span> <span class="hljs-number">25</span>

<span class="hljs-attr">Tag:</span> <span class="hljs-number">0x03</span> <span class="hljs-string">(Address)</span>
<span class="hljs-attr">Length:</span> <span class="hljs-number">10</span> <span class="hljs-string">Chars</span>
<span class="hljs-attr">Value:</span> <span class="hljs-string">Labim</span> <span class="hljs-string">Mall</span>
</code></pre>
<p>This TLV scheme allows us to represent information about a person using a structured format that can be easily encoded, decoded, and processed by software systems. Each piece of information (name, age, address) is identified by a unique tag, and the length field ensures that the data can be properly parsed and interpreted.</p>
<p>The final string in a TLV format defining the data above - constitutes to be</p>
<pre><code class="lang-yaml"><span class="hljs-string">0105Alice0202250310Labim</span> <span class="hljs-string">Mall</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Automating Instance Start/Stop with System Manager State Manager]]></title><description><![CDATA[Introduction:
In the realm of cloud computing, cost optimization reigns supreme. Within the vast ecosystem of AWS, where resources are provisioned and billed on a pay-as-you-go basis, maximizing efficiency becomes paramount. One significant area for ...]]></description><link>https://khalti.engineering/automating-instance-startstop-with-system-manager-state-manager</link><guid isPermaLink="true">https://khalti.engineering/automating-instance-startstop-with-system-manager-state-manager</guid><category><![CDATA[ssm state manager]]></category><category><![CDATA[AWS]]></category><category><![CDATA[AWS Systems Manager]]></category><category><![CDATA[Devops]]></category><category><![CDATA[cost-optimisation]]></category><dc:creator><![CDATA[Aman Maharjan]]></dc:creator><pubDate>Wed, 13 Mar 2024 09:59:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1710323842439/56db36b7-e6e4-46a6-a44c-915be6d8e8ab.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn-images-1.medium.com/max/1600/1*LVdbBtSBD82MmwHK1CLd7Q.jpeg" alt /></p>
<h3 id="heading-introduction">Introduction:</h3>
<p>In the realm of cloud computing, cost optimization reigns supreme. Within the vast ecosystem of AWS, where resources are provisioned and billed on a pay-as-you-go basis, maximizing efficiency becomes paramount. One significant area for potential savings lies in the management of EC2 and RDS instances. Not every instance needs to run incessantly; often, non-production instances or those not serving round-the-clock operations can be safely halted to reduce costs.</p>
<p>However, manually starting and stopping instances on a daily basis can be a tedious and error-prone task for cloud users. This is where automation steps in, offering a streamlined solution to manage instance lifecycle efficiently. AWS System Manager’s State Manager provides a robust framework for automating such tasks, ensuring instances are active precisely when needed.</p>
<h3 id="heading-creating-iam-role-and-policy">Creating IAM Role and Policy:</h3>
<p>To empower System Manager with the necessary permissions, a dedicated IAM role and policy must be configured. Lets create a IAM policy with name <strong>StopStartInstancePolicy</strong> encompassing actions like describing, starting, stopping, and rebooting EC2 and RDS instances, grants System Manager the requisite authority over resources</p>
<pre><code class="lang-plaintext">{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ec2:Describe*",
                "ec2:Start*",
                "ec2:Stop*",
                "ec2:Reboot*",
                "rds:Describe*",
                "rds:Start*",
                "rds:Stop*",
                "rds:Reboot*"
            ],
            "Resource": "*"
        }
    ]
}
</code></pre>
<p>Now lets create a IAM Role with name <strong>StopStartInstanceRole</strong> with a <strong>custom trust policy</strong> allowing System Manager (<a target="_blank" href="http://ssm.amazonaws.com">ssm.amazonaws.com</a>) to assume the role and attach the above created policy.</p>
<p><strong>Trust Relationship:</strong></p>
<pre><code class="lang-plaintext">{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "ssm.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
</code></pre>
<h3 id="heading-setting-up-state-manager-association">Setting Up State Manager Association:</h3>
<p>With permissions in place, State Manager associations are configured to orchestrate instance start and stop workflows. Utilizing the “<strong>AWS-StartEC2Instance</strong>” and “<strong>AWS-StopEC2Instance</strong>” documents, associations are defined to trigger instance actions based on a specified schedule.</p>
<p>For starting instances, create an association named “<strong>StartInstances</strong>”, defining a schedule using a CRON schedule builder. This association triggers the “<strong>AWS-StartEC2Instance</strong>” document, initiating instance start operations at the specified time.</p>
<p><em>AWS System Manager -&gt; Node Management -&gt; State Manager</em></p>
<p><strong>Create Association:</strong></p>
<p><strong>Name(Provide a name for your Association):</strong> StartInstances</p>
<p><strong>Document</strong>: AWS-StartEC2Instance</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*-OCwupoRXqUs5S1UsTf6og.png" alt /></p>
<p><strong>Input parameters:</strong> <em>InstanceId -&gt; Enable Show interactive instance picker -&gt; Show all instances -&gt; Select the instance</em></p>
<p><strong>AutomationAssumeRole:</strong> Add the role created above</p>
<p><strong>Specify schedule:</strong> On Schedule</p>
<p><strong>CRON schedule builder</strong>: Daily</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*wMKqnKcNL_1DR2p-NqvB_A.png" alt /></p>
<p>Add time to start the instance</p>
<p>If you want to skip the cron for first run select</p>
<p><em>Apply association only at the next specified cron interval</em></p>
<p>Similarly, for stopping instances, followed the same process, creating an association named “<strong>StopInstances</strong>” and employing the “<strong>AWS-StopEC2Instance</strong>” document. This association halts instances according to the configured schedule, ensuring resources are inactive during non-operational hours.</p>
<h3 id="heading-conclusion">Conclusion:</h3>
<p>By leveraging System Manager’s State Manager, AWS users can automate the start and stop lifecycle of EC2 instances, optimizing costs without sacrificing operational efficiency. Through a carefully orchestrated setup involving IAM roles, policies, and State Manager associations, the burden of manual instance management is alleviated, enabling organizations to focus on core business objectives while maximizing the value derived from AWS services.</p>
]]></content:encoded></item><item><title><![CDATA[Examination Preparation Materials - Model Questions]]></title><description><![CDATA[The marking scheme and distribution for each chapter shall be as follows
ChapterChapter NameHrsMarks1Fintech in Nepal6 hrs10 marks2Fintech General Practices and high level understanding5 hrs10 marks3Applications in Fintech4 hrs15 marks4Engineering Pr...]]></description><link>https://khalti.engineering/model-questions-ioe-applied-fintech-engineering-course-by-khalti</link><guid isPermaLink="true">https://khalti.engineering/model-questions-ioe-applied-fintech-engineering-course-by-khalti</guid><category><![CDATA[Exam Model Questions]]></category><category><![CDATA[applied-fintech-engineering]]></category><category><![CDATA[ioe-elective]]></category><category><![CDATA[pulchowk-campus]]></category><category><![CDATA[Tribhuvan University]]></category><dc:creator><![CDATA[Dhruba Adhikari]]></dc:creator><pubDate>Wed, 13 Mar 2024 09:45:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/QJDzYT_K8Xg/upload/2b2fb48ecc277ed8e54ec74bd1aec088.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The marking scheme and distribution for each chapter shall be as follows</p>
<table><tbody><tr><td><p><strong>Chapter</strong></p></td><td><p><strong>Chapter Name</strong></p></td><td><p><strong>Hrs</strong></p></td><td><p><strong>Marks</strong></p></td></tr><tr><td><p>1</p></td><td><p>Fintech in Nepal</p></td><td><p>6 hrs</p></td><td><p>10 marks</p></td></tr><tr><td><p>2</p></td><td><p>Fintech General Practices and high level understanding</p></td><td><p>5 hrs</p></td><td><p>10 marks</p></td></tr><tr><td><p>3</p></td><td><p>Applications in Fintech</p></td><td><p>4 hrs</p></td><td><p>15 marks</p></td></tr><tr><td><p>4</p></td><td><p>Engineering Practices for Fintech at Scale</p></td><td><p>12 hrs</p></td><td><p>20 marks</p></td></tr><tr><td><p>5</p></td><td><p>Fintech Project Management:</p></td><td><p>8 Hrs</p></td><td><p>10 marks</p></td></tr><tr><td><p>6</p></td><td><p>Getting Prepared in Devops</p></td><td><p>6 hrs</p></td><td><p>5 marks</p></td></tr><tr><td><p>7</p></td><td><p>The Career Path in Fintech Industry</p></td><td><p>4 hrs</p></td><td><p>10 marks</p></td></tr></tbody></table>

<p>Please find below the chapter-wise model questions for the course. Additional sample questions will be added as the course advances.</p>
<h3 id="heading-chapter-1-fintech-in-nepal"><mark>Chapter 1 - Fintech in Nepal</mark></h3>
<p><strong>6 Hrs / 10 Marks</strong></p>
<table><tbody><tr><td><p><strong>QNo</strong></p></td><td><p><strong>Question</strong></p></td><td><p><strong>Marks</strong></p></td></tr><tr><td><p>1.1</p></td><td><p>What is the difference between PSO and PSP ? Provide examples of one PSO and one PSP in Nepal and justify why they are defined so based upon the type of business.</p></td><td><p>10</p></td></tr><tr><td><p>1.2</p></td><td><p>What is a Neo-Bank, and why is it different from a traditional Bank?</p></td><td><p>10</p></td></tr><tr><td><p>1.3</p></td><td><p>What is a virtual private address (VPA) and how UPI India is using it to standardize the payment ecosystem. Explain with a practical use case.</p></td><td><p>10</p></td></tr><tr><td><p>1.4</p></td><td><p>Explain TLV format and construct a TLV scheme of your own for any sample data structure of your own.</p></td><td><p>10</p></td></tr></tbody></table>

<h3 id="heading-chapter-2-fintech-general-practices-and-high-level-understanding"><mark>Chapter 2 - Fintech General Practices and High Level Understanding</mark></h3>
<p><strong>5 Hrs / 10 Marks</strong></p>
<table><tbody><tr><td><p><strong>QNo</strong></p></td><td><p><strong>Question</strong></p></td><td><p><strong>Marks</strong></p></td></tr><tr><td><p>2.1</p></td><td><p>What are sessions and settlements in financial ecosystem</p></td><td><p>10</p></td></tr><tr><td><p>2.2</p></td><td><p>What is a four party model in fintech ecosystem</p></td><td><p>10</p></td></tr><tr><td><p>2.3</p></td><td><p>What is tokenization in the fintech ecosystem? Explain with a simple use case</p></td><td><p>10</p></td></tr><tr><td><p>2.4</p></td><td><p>Define MDR and MSF</p></td><td><p>10</p></td></tr><tr><td><p>2.5</p></td><td><p>What is Idempotency in Payment - elaborate with a simple example (no coding required)</p></td><td><p>10</p></td></tr></tbody></table>

<h3 id="heading-chapter-3-applications-in-fintech"><mark>Chapter 3 - Applications in Fintech</mark></h3>
<p><strong>4 hrs / 15 Marks</strong></p>
<table><tbody><tr><td><p><strong>QNo</strong></p></td><td><p><strong>Question</strong></p></td><td><p><strong>Marks</strong></p></td></tr><tr><td><p>3.1</p></td><td><p>What is a payment rail application ? Give an example on how a payment rail application integrates into some software.</p></td><td><p>15</p></td></tr><tr><td><p>3.2</p></td><td><p>Define RegTech with some examples</p></td><td><p>15</p></td></tr><tr><td><p>3.3</p></td><td><p>Why is crypto currency regarded as anonymous ? Provide 3 reasons and explain them.</p></td><td><p>15</p></td></tr><tr><td><p>3.4</p></td><td><p>Explain 3 fintech application areas with a short explanation to each</p></td><td><p>15</p></td></tr><tr><td><p>3.5</p></td><td><p>What is Fintech as a service ? explain with example</p></td><td><p>15</p></td></tr></tbody></table>

<h3 id="heading-chapter-4-engineering-practices-for-fintech-at-scale"><mark>Chapter 4 - Engineering Practices for Fintech at Scale</mark></h3>
<p><strong>12 Hrs / 20 Marks</strong></p>
<table><tbody><tr><td><p><strong>QNo</strong></p></td><td><p><strong>Question</strong></p></td><td><p><strong>Marks</strong></p></td></tr><tr><td><p>4.1</p></td><td><p>What is a multi-tenant system ? Explain two different implementations of multi-tenant systems that should run ideally with a single codebase.</p></td><td><p>5 + 15</p></td></tr><tr><td><p>4.2</p></td><td><p>Write 4 design patterns and explain each of them in details</p></td><td><p>20</p></td></tr><tr><td><p>4.3</p></td><td><p>Imagine the Rain phenomenon as a software process. Now model the process with components and data flow such that it works as an asynchronous system</p></td><td><p>20</p></td></tr><tr><td><p>4.4</p></td><td><p>Explain symmetric and asymmetric encryption in details with separate use cases</p></td><td><p>20</p></td></tr><tr><td><p>4.5</p></td><td><p>Explain a single scenario where symmetric and asymmetric encryption are used mutually together</p></td><td><p>20</p></td></tr><tr><td><p>4.6</p></td><td><p>Define Infrastructure as Code (IaC), Containerization with examples</p></td><td><p>20</p></td></tr><tr><td><p>4.7</p></td><td><p>Define CI/CD and explain a practical scenario of that</p></td><td><p>20</p></td></tr><tr><td><p>4.8</p></td><td><p>Explain RTO and RPO, and Define SLA, SLO, SLI in Site reliability engineering</p></td><td><p>10 + 10</p></td></tr><tr><td><p>4.9</p></td><td><p>Define Horizontal Scaling and Vertical Scaling. Explain Greenfield and Brownfield strategy of software development</p></td><td><p>10 + 10</p></td></tr></tbody></table>

<h3 id="heading-chapter-5-fintech-project-management"><mark>Chapter 5 - Fintech Project Management</mark></h3>
<p><strong>8 Hrs / 10 Marks</strong></p>
<table><tbody><tr><td><p><strong>QNo</strong></p></td><td><p><strong>Question</strong></p></td><td><p><strong>Marks</strong></p></td></tr><tr><td><p>5.1</p></td><td><p>Differentiate product management and project management</p></td><td><p>10</p></td></tr><tr><td><p>5.2</p></td><td><p>Differentiate Waterfall model and Agile model for software development</p></td><td><p>10</p></td></tr><tr><td><p>5.3</p></td><td><p>What is the difference between Product Owner and Scrum master ?</p></td><td><p>10</p></td></tr><tr><td><p>5.4</p></td><td><p>Mention any 5 principles from the agile manifesto</p></td><td><p>10</p></td></tr></tbody></table>

<h3 id="heading-chapter-6-getting-prepared-in-devops"><mark>Chapter 6 - Getting Prepared in DevOps</mark></h3>
<p><strong>6 Hrs / 5 Marks</strong></p>
<table><tbody><tr><td><p><strong>QNo</strong></p></td><td><p><strong>Question</strong></p></td><td><p><strong>Marks</strong></p></td></tr><tr><td><p>6.1</p></td><td><p>What is the difference between git pull, git merge and git fetch ?</p></td><td><p>5</p></td></tr><tr><td><p>6.2</p></td><td><p>What is the use of a compose file in docker ?</p></td><td><p>5</p></td></tr><tr><td><p>6.3</p></td><td><p>Create a sample pipeline in pseudo code</p></td><td><p>5</p></td></tr><tr><td><p>6.4</p></td><td><p>Explain the use of message bus in software design - with any one technology that you know</p></td><td><p>5</p></td></tr><tr><td><p>6.5</p></td><td><p>What is semantic versioning</p></td><td><p>5</p></td></tr><tr><td><p>6.6</p></td><td><p>Define SLA, SLO, SLI in Site Reliability Engineering</p></td><td><p>5</p></td></tr><tr><td><p>6.7</p></td><td><p>Differentiate Horizontal Scaling and Vertical Scaling</p></td><td><p>5</p></td></tr></tbody></table>

<h3 id="heading-chapter-7-the-career-path-in-fintech-industry"><mark>Chapter 7 - The Career Path in Fintech Industry</mark></h3>
<p><strong>4 Hrs / 10 Marks</strong></p>
<table><tbody><tr><td><p><strong>QNo</strong></p></td><td><p><strong>Question</strong></p></td><td><p><strong>Marks</strong></p></td></tr><tr><td><p>7.1</p></td><td><p>What are the different areas of the Fintech Industry ? Provide 4 different types of Fintech industry components and write a short description of each.</p></td><td><p>10</p></td></tr><tr><td><p>7.2</p></td><td><p>What is a Risk and how Risk based scoring can be used in Decision engines ? Explain with some examples.</p></td><td><p>10</p></td></tr><tr><td><p>7.3</p></td><td><p>Mention 3 different career areas as a fintech engineer and provide a general explanation of the career.</p></td><td><p>10</p></td></tr><tr><td><p>7.4</p></td><td><p>Write 3 scopes of Artificial intelligence in Fintech Industry</p></td><td><p>10</p></td></tr><tr><td><p>7.5</p></td><td><p>Write 3 scopes of Blockchain implementation in Fintech industry</p></td><td><p>10</p></td></tr></tbody></table>]]></content:encoded></item><item><title><![CDATA[Implementing Self-Managed Kubernetes Clusters]]></title><description><![CDATA[In the realm of modern cloud-native application development, the ability to have applications auto-scaled to handle varying traffic is nothing short of a blessing. Scaling resources according to usage becomes a fundamental aspect of ensuring seamless...]]></description><link>https://khalti.engineering/implementing-self-managed-kubernetes-clusters</link><guid isPermaLink="true">https://khalti.engineering/implementing-self-managed-kubernetes-clusters</guid><category><![CDATA[self-managed]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[kubeadm]]></category><category><![CDATA[kubespray]]></category><category><![CDATA[ansible]]></category><category><![CDATA[automation]]></category><category><![CDATA[tools]]></category><dc:creator><![CDATA[Aman Maharjan]]></dc:creator><pubDate>Mon, 12 Feb 2024 11:42:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/9cXMJHaViTM/upload/a15068071fd1be666074031fb8b00013.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the realm of modern cloud-native application development, the ability to have applications auto-scaled to handle varying traffic is nothing short of a blessing. Scaling resources according to usage becomes a fundamental aspect of ensuring seamless user experiences.</p>
<p>While setting up and managing Kubernetes clusters is relatively straightforward with managed services from cloud providers like AWS (EKS), GCP (GKE), Azure (AKS), and DigitalOcean Kubernetes Cluster, the landscape changes when considering on-premises data centers. This blog post delves into the challenges and opportunities associated with implementing and maintaining self-managed Kubernetes clusters, covering distribution options, configuration techniques, best practices, essential add-ons, and potential challenges.</p>
<p>So when I started using and suggesting Kubernetes for production, I initially leaned towards managed services, mostly EKS and GKE. However, for deepening my understanding of Kubernetes, I delved into self-managed options through labs and pursued my CKA certification. Later on, after honing my skills, implementing self-managed Kubernetes clusters for production proved to be a valuable experience, offering numerous advantages over its challenges.</p>
<h3 id="heading-when-to-use-self-managed-kubernetes-clusters">When to Use Self-Managed Kubernetes Clusters:</h3>
<p>Self-managed Kubernetes clusters become a compelling choice when:</p>
<p><strong>Advanced Orchestration Requirements</strong>: Applications requiring advanced orchestrations such as autoscaling, rolling updates, and rollbacks benefit from the flexibility and control of self-managed clusters.</p>
<p><strong>Microservices Architecture:</strong> For architectures following a microservices or multiservice pattern, where services need to scale independently and communicate efficiently.</p>
<p><strong>On-Premises Constraints:</strong> Organizational policies or legal constraints may limit the use of public clouds or managed clusters, making self-management the preferred option. Some organizations simply can’t use the public cloud, as they are bound by stringent regulations related to compliance and data privacy issues</p>
<p><strong>Dedicated Team</strong>: Having a dedicated team for engineering and maintenance ensures proper care and understanding of the entire system.</p>
<p><strong>Control Over Management Layer:</strong> Self-managed clusters provide control over the management layer, unlike fully managed Kubernetes services in the cloud that limit configuration access to the cluster master.</p>
<p><strong>Multi-tenant applications:</strong> Applications designed to serve multiple customers from a single app instance benefit from Kubernetes’ ability to provide a secure isolated environment for each tenant.</p>
<p><strong>Cost</strong>: Cost is probably the most important reason to run Kubernetes on-premises. Running all of your applications in the public cloud can get expensive at scale. Specifically, if your applications rely on ingesting and processing large amounts of data, a public cloud can get extremely expensive. If you have existing data centers on-premises or in a co-location-hosted facility, running Kubernetes on-premises can be an effective way to reduce your operational costs.</p>
<h3 id="heading-options-for-kubernetes-distribution">Options for Kubernetes Distribution:</h3>
<p>Several options are available, including:</p>
<p><strong>Kubeadm</strong>: A popular choice for bootstrapping Kubernetes clusters, offering simplicity and flexibility. <a target="_blank" href="https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/">Kubeadm Documentation</a></p>
<p><strong>RKE/RKE2:</strong> Known for ease of use and reliability, suitable for both small and large-scale deployments. <a target="_blank" href="https://docs.rke2.io/install/quickstart">RKE2 Documentation</a></p>
<p><strong>K3s</strong>: A lightweight distribution designed for resource-constrained environments, suitable for edge computing. <a target="_blank" href="https://docs.k3s.io/installation">K3s Documentation</a></p>
<p><strong>Kubespray</strong>: A community project deploying production-ready Kubernetes clusters using Ansible. <a target="_blank" href="https://github.com/kubernetes-sigs/kubespray/blob/master/docs/setting-up-your-first-cluster.md">Kubespray Documentation</a></p>
<p><strong>EKS Anywhere, VMware Tanzu, and OpenShift</strong>: Solutions from major vendors offering robust features and enterprise support. <a target="_blank" href="https://anywhere.eks.amazonaws.com/docs/getting-started/">EKS Anywhere Documentation</a> | <a target="_blank" href="https://tanzu.vmware.com/">VMware Tanzu</a> | <a target="_blank" href="https://www.okd.io/installation/">OpenShift Documentation</a></p>
<p><strong>Custom Distributions</strong>: Tailoring Kubernetes clusters to specific needs, especially in scenarios where existing distributions don’t meet specific requirements.</p>
<p>Understanding the architecture of Kubernetes control plane through initiatives like Kelsey Hightower’s “<a target="_blank" href="https://github.com/kelseyhightower/kubernetes-the-hard-way">Kubernetes the Hard Way</a>” can enhance the expertise of your team.</p>
<h3 id="heading-configuration-and-automation">Configuration and Automation:</h3>
<p>Configuration details for each distribution are available on their official sites. Utilizing Infrastructure as Code (IaC) tools like Terraform can automate the provisioning of virtual machines, while configuration management tools like Ansible can handle packages, dependencies, and services on both master and worker nodes.</p>
<p>Integrating this process into a continuous integration/continuous deployment (CI/CD) pipeline using tools like Jenkins or GitHub Actions streamlines the entire setup, ensuring consistency and reproducibility. Consider implementing GitOps principles, where the entire cluster’s configuration is stored in a Git repository for version control and easy rollback of changes.</p>
<h3 id="heading-best-practices">Best Practices:</h3>
<p>Maintaining self-managed Kubernetes clusters involves several best practices, including:</p>
<p><strong>Resource Planning:</strong> Understand the resource requirements of your applications and scale the cluster accordingly.</p>
<p><strong>Regular Updates:</strong> Stay current with Kubernetes releases and regularly update your cluster to benefit from the latest features, enhancements, and security patches.</p>
<p><strong>Backup and Disaster Recovery</strong>: Implement robust backup and disaster recovery strategies to protect your cluster data and configurations.</p>
<p><strong>Monitoring and Logging:</strong> Utilize monitoring tools like Prometheus and Grafana, and implement logging mechanisms such as Elasticsearch and Fluentd to troubleshoot issues proactively and understand the cluster’s performance.</p>
<p><strong>Horizontal Pod Autoscaling (HPA)</strong>: Leverage Kubernetes HPA to automatically adjust the number of running pods in response to changing demand.</p>
<p><strong>Custom Resource Definitions (CRDs):</strong> Use CRDs to extend Kubernetes and define custom resources specific to your applications.</p>
<h3 id="heading-required-tools-add-ons-and-plugins">Required Tools, Add-ons, and Plugins:</h3>
<p>Enhance your Kubernetes cluster with essential tools, add-ons and plugins:</p>
<p><strong>Dashboard</strong>: A web interface for Kubernetes. <a target="_blank" href="https://github.com/kubernetes/dashboard#kubernetes-dashboard">Dashboard Documentation</a></p>
<p><strong>Ingress Controller</strong>: Manages external access to services within a cluster, providing routing and load balancing. <a target="_blank" href="https://github.com/kubernetes/ingress-nginx">Ingress Nginx Documentation</a></p>
<p><strong>Metric Server:</strong> Collects and provides resource usage metrics. <a target="_blank" href="https://github.com/kubernetes-sigs/metrics-server">Metric Server Documentation</a></p>
<p><strong>Cert Manager</strong>: Automates the management and issuance of TLS certificates. <a target="_blank" href="https://cert-manager.io/">Cert Manager Documentation</a></p>
<p><strong>Prometheus and Grafana:</strong> Monitoring and observability tools for tracking and visualizing performance metrics. <a target="_blank" href="https://github.com/prometheus-community/helm-charts/blob/main/charts/kube-prometheus-stack/README.md">Kube Prometheus Stack Documentation</a></p>
<p><strong>Istio</strong>: Implements a service mesh for enhanced observability, security, and traffic management. <a target="_blank" href="https://istio.io/">Istio Documentation</a></p>
<p><strong>Knative</strong>: For building and managing serverless applications on Kubernetes. <a target="_blank" href="https://knative.dev/docs/">Knative Documentation</a></p>
<p><strong>KEDA</strong>: Event-Driven autoscaling for Kubernetes. <a target="_blank" href="https://keda.sh/">KEDA Documentation</a></p>
<p><strong>Velero</strong>: A tool for safely backing up, restoring, performing disaster recovery, and migrating Kubernetes cluster resources and persistent volumes. <a target="_blank" href="https://velero.io/">Velero Documentation</a></p>
<p><strong>KubeVirt</strong>: Run virtual machines on Kubernetes. <a target="_blank" href="https://kubevirt.io/user-guide/#/installation/installation">KubeVirt Documentation</a></p>
<p><strong>ClusterMan</strong>: Autoscale and manage your compute clusters. <a target="_blank" href="https://github.com/Yelp/clusterman">ClusterMan Documentation</a></p>
<p><strong>Lens</strong>: IDE for Kubernetes<a target="_blank" href="https://k8slens.dev/">Lens</a></p>
<p><strong>Kubectl Snapshot</strong>: Snapshot Cluster. <a target="_blank" href="https://github.com/fbrubbo/kubectl-snapshot">Kubectl Snapshot Documentation</a></p>
<p><strong>Node Problem Detector</strong>: Aims to make various node problems visible to the upstream layers in the cluster management stack. <a target="_blank" href="https://github.com/kubernetes/node-problem-detector">Node Problem Detector Documentation</a></p>
<p><strong>ArgoCD</strong>: A declarative, GitOps continuous delivery tool for Kubernetes. <a target="_blank" href="https://github.com/argoproj/argo-cd">ArgoCD Documentation</a></p>
<h3 id="heading-challenges">Challenges:</h3>
<p>Identifying and addressing challenges associated with implementing and maintaining self-managed Kubernetes clusters is crucial. Common challenges include:</p>
<p><strong>Resource Constraints</strong>: Managing resources efficiently, especially in on-premises environments with limited hardware.</p>
<p><strong>Compatibility Issues</strong>: Ensuring compatibility between different Kubernetes components, plugins, and add-ons.</p>
<p><strong>Auto-scaling:</strong> Auto-scaling based on workload needs can help save resources. This is difficult to achieve for bself managed Kubernetes clusters unless you are using IaC like Terraform with event based trigger to provision Virtual Machines as mentioned above or a bare metal automation platform such as open-source Ironic or Platform9’s Managed Bare Metal.</p>
<p><strong>Troubleshooting Complexity:</strong> Diagnosing and resolving issues can be complex, necessitating a skilled and experienced team.</p>
<p><strong>Scale and Performance</strong>: Ensuring the cluster can scale and perform optimally as workloads increase.</p>
<p><strong>Upgrades and Rollbacks:</strong> Managing upgrades smoothly and safely, including rollback procedures in case of issues.</p>
<p><strong>Security Patching</strong>: Timely application of security patches to protect against vulnerabilities.</p>
<p>also published at <a target="_blank" href="https://medium.com/@mhrznamn068/implementing-self-managed-kubernetes-clusters-on-premises-04018972f3ef">medium</a> on the author's blog.</p>
]]></content:encoded></item><item><title><![CDATA[Generating KUBECONFIG: Automating Role and Cluster Role Creation (RBAC) with Helm and Jenkins on a Self Managed Kubernetes Cluster]]></title><description><![CDATA[In the ever-evolving landscape of cloud-native technologies, Kubernetes has emerged as the de facto standard for container orchestration. Its robustness and flexibility empower organizations to deploy and manage their applications efficiently. Howeve...]]></description><link>https://khalti.engineering/generating-kubeconfig-automatically-with-helm-jenkins</link><guid isPermaLink="true">https://khalti.engineering/generating-kubeconfig-automatically-with-helm-jenkins</guid><category><![CDATA[Kubernetes]]></category><category><![CDATA[kubeconfig]]></category><category><![CDATA[Helm]]></category><category><![CDATA[rbac]]></category><category><![CDATA[rancher]]></category><category><![CDATA[Jenkins]]></category><category><![CDATA[role-based-access-control]]></category><dc:creator><![CDATA[Anish Sedhai]]></dc:creator><pubDate>Mon, 12 Feb 2024 11:39:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/jOqJbvo1P9g/upload/43450470717dde23495da51561f2ce51.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the ever-evolving landscape of cloud-native technologies, Kubernetes has emerged as the de facto standard for container orchestration. Its robustness and flexibility empower organizations to deploy and manage their applications efficiently. However, with great power comes great responsibility, particularly in terms of security. Access control, authentication, and authorization are critical aspects of Kubernetes security that demand meticulous attention.</p>
<p>Accessing a Kubernetes cluster can be accomplished through various methods, including:</p>
<ol>
<li><p>Kubectl: The primary command-line interface for interacting with Kubernetes clusters. It requires authentication credentials to communicate with the cluster’s API server.</p>
</li>
<li><p>API Requests: Applications and services can interact with the Kubernetes API server directly, using client libraries or HTTP requests. Again, authentication is necessary to verify the identity of the requester.</p>
</li>
<li><p>Kubernetes Dashboard: A web-based user interface for Kubernetes clusters. It also requires authentication for access.</p>
</li>
<li><p>Service Accounts: Kubernetes assigns each pod a service account, enabling applications running within pods to authenticate with the Kubernetes API and perform actions on the cluster.</p>
</li>
</ol>
<p><strong>Authentication and Authorization in Kubernetes:</strong></p>
<p>Authentication is the process of verifying the identity of a user, system, or application attempting to access the Kubernetes cluster. Without proper authentication mechanisms in place, unauthorized entities could gain access to sensitive resources, posing significant security risks.</p>
<p>Authorization, on the other hand, determines what actions a user, system, or application is permitted to perform within the Kubernetes cluster. Even authenticated users must be authorized to perform specific operations, ensuring that they only have access to the resources they need.</p>
<p>In Kubernetes, authentication and authorization are typically handled through various mechanisms:</p>
<ol>
<li><p>Certificates: Users can authenticate with Kubernetes using client certificates issued by a Certificate Authority (CA). Kubernetes API servers verify these certificates to authenticate users.</p>
</li>
<li><p>Tokens: Users can also authenticate using bearer tokens, which are issued by the Kubernetes API server or an external authentication provider. These tokens grant access to specific resources based on configured policies.</p>
</li>
<li><p>OIDC (OpenID Connect): Kubernetes supports OIDC authentication, allowing users to authenticate using identity providers such as Google, Microsoft Azure, or Okta. OIDC tokens are exchanged for Kubernetes tokens, which are then used for authorization.</p>
</li>
<li><p>Static Password Files: While not recommended for production environments, Kubernetes can authenticate users using static password files. However, this method lacks the scalability and security features of other authentication mechanisms.</p>
</li>
<li><p>Static Token Files: Kubernetes supports authentication using static token files. Users can authenticate by presenting a token stored in a file. While this method is straightforward, it lacks the security features and scalability of other authentication mechanisms.</p>
</li>
</ol>
<p><strong>AUTHENTICATION</strong> in kubernetes is explained in detail in this official documentation : <a target="_blank" href="https://kubernetes.io/docs/reference/access-authn-authz/authentication/">https://kubernetes.io/docs/reference/access-authn-authz/authentication/</a></p>
<p>Role-Based Access Control (RBAC) is the primary authorization mechanism in Kubernetes, allowing administrators to define roles and role bindings to control access to cluster resources. Roles specify a set of permissions, while role bindings associate roles with users, groups, or service accounts.</p>
<p>Before RBAC became the standard for authorization in Kubernetes, Attribute-Based Access Control (ABAC) was a commonly used approach. ABAC grants access based on attributes associated with users, such as roles, departments, or locations.</p>
<p>However, ABAC has several disadvantages:</p>
<ol>
<li><p>Complexity: Managing a large number of attributes and policies can quickly become complex and difficult to maintain.</p>
</li>
<li><p>Scalability: As the number of users and resources grows, ABAC policies can become unwieldy and resource-intensive to evaluate.</p>
</li>
<li><p>Flexibility: ABAC policies often lack granularity, making it challenging to enforce fine-grained access control.</p>
</li>
</ol>
<p>RBAC, on the other hand, offers several advantages over ABAC:</p>
<ol>
<li><p>Simplicity: RBAC simplifies access control by defining roles with specific permissions and associating them with users or groups.</p>
</li>
<li><p>Scalability: RBAC scales more efficiently, as role definitions are easier to manage and evaluate compared to complex attribute-based policies.</p>
</li>
<li><p>Granularity: RBAC allows for finer-grained access control, enabling administrators to specify exactly what actions users can perform on specific resources.</p>
</li>
</ol>
<p>Below is the link of the repository where the files are present:</p>
<h2 id="heading-github-anishsedhaiirbac-helm-jenkinfile-and-bash-script-to-create-rolecluster-using-helm-charthttpsgithubcomanishsedhaiirbac-helmsourcepostpage-bcd70b9934b9"><a target="_blank" href="https://github.com/anishsedhaii/rbac-helm?source=post_page-----bcd70b9934b9--------------------------------"><strong>GitHub - anishsedhaii/rbac-helm: Jenkinfile and Bash script to create role/cluster using Helm Chart…</strong></a></h2>
<p>Let’s start with the Jenkinsfile first.</p>
<pre><code class="lang-plaintext">pipeline {
    agent {
        label "some_agent"
    }
    environment {
      CLUSTER1_MASTER_IP = ""
      CLUSTER2_MASTER_IP = ""
      CLUSTER3_MASTER_IP = ""
      SSH_KEY = "SSH_KEY_PATH"
    }
    parameters {
      choice(name: 'CLUSTER', choices: ['Cluster1', 'Cluster2' , 'Cluster3'], description: 'Choose cluster to implement RBAC')  
      choice(name: 'ROLE', choices: ['ClusterRole', 'Role'], description: 'Choose Role to deploy')
      string(name: 'NAMESPACE', defaultValue: '', description: 'Enter namespace if you want to create role for specific namespace')
      string(name: 'USERNAME', defaultValue: '', description: 'Enter username ex. firstname.lastname')
      string(name: 'EMAIL', defaultValue: '', description: 'Enter email of the user with @organization.com')
      choice(name: 'ACTION', choices: ['plan', 'apply'], description: 'Choose Action')  
    }
    stages {
      stage('Decide Master Node') {
        steps {
          script {
            def MASTER_IP
                    if (params.CLUSTER == 'Cluster1') {
                        MASTER_IP = CLUSTER1_MASTER_IP
                    } else if (params.CLUSTER == 'Cluster2') {
                        MASTER_IP = CLUSTER2_MASTER_IP
                    } else if (params.CLUSTER == 'Cluster3') {
                        MASTER_IP = CLUSTER3_MASTER_IP
                    }
                    env.MASTER_IP = MASTER_IP
                    sh "echo MASTER_IP: ${MASTER_IP}"
          }
        }
      }
      stage('Copy KUBECONFIG from MasterNode') {
        steps {
          dir("${WORKSPACE}") {
          sh """
            scp -i ${SSH_KEY} root@${env.MASTER_IP}:/etc/rancher/rke2/rke2.yaml kubeconfig.yaml
            sed -i "s|https://127.0.0.1:6443|https://${env.MASTER_IP}:6443|g" kubeconfig.yaml
          """
          }
        }
      }
      stage('Deploy RBAC') {
        steps {
          dir("${WORKSPACE}") {
          sh """
            chmod a+x config.sh
            /bin/bash config.sh 
          """
          }
        }
      }
      stage('Extract Config'){
        steps{
          dir("${WORKSPACE}") {
            sh """
              chmod a+x generateconfig.sh
              /bin/bash generateconfig.sh
            """
          }
        }
      }
    }  
    post {
        always {
            script {
                emailext attachmentsPattern: "kubeconfig_user.yaml",
                    body: 'Download the kubeconfig file to connect to the cluster',
                    subject: 'Kubeconfig for Cluster connection',
                    to: "$EMAIL"
            }
        }
      aborted {
          echo 'Pipeline was aborted'
      }
      failure {
          mail to: "aniecesedhai@gmail.com",
          subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
          body: "Something is wrong with ${env.BUILD_URL}"
      }
    }
}
</code></pre>
<p><strong>Stages:</strong></p>
<ul>
<li><p>Decide Master Node: Determines the master node’s IP address based on the selected cluster.</p>
</li>
<li><p>Copy KUBECONFIG from MasterNode: Copies the kubeconfig file from the master node to the workspace directory and updates the server URL.</p>
</li>
<li><p>Deploy RBAC: Executes a configuration script (<code>config.sh</code>) to deploy RBAC based on the selected parameters.</p>
</li>
<li><p>Extract Config: Runs a script (<code>generateconfig.sh</code>) to generate a configuration file.</p>
</li>
</ul>
<p><strong>Post-build Actions:</strong></p>
<ul>
<li><p>Always: Sends an email with the kubeconfig file (<code>kubeconfig_user.yaml</code>) attached, allowing users to download and connect to the cluster.</p>
</li>
<li><p>Aborted: Prints a message if the pipeline is aborted.</p>
</li>
<li><p>Failure: Sends an email notification to the specified email address if the pipeline fails, providing details about the failed build.</p>
</li>
</ul>
<p>This Jenkinsfile orchestrates the automation process for deploying Helm charts and configuring RBAC in Kubernetes clusters. However, it’s worth noting that the Jenkins pipeline itself can be skipped if desired, and the provided scripts (<code>config.sh</code> and <code>generateconfig.sh</code>) can be used independently for deploying the Helm chart and generating kubeconfig files.</p>
<p>Now lets move towards the config.sh script</p>
<pre><code class="lang-plaintext">#!/bin/bash

set -xe

ACTION=$ACTION
ROLE=$ROLE
USERNAME=$USERNAME
NAMESPACE=$NAMESPACE
export KUBECONFIG=kubeconfig.yaml
plan () {
    if [ $ROLE == "ClusterRole" ]; then
        helm upgrade $USERNAME --install roles/ --dry-run \
        --set clusterrole.name=clusterrole --set clusterrolebinding.name=clusterrole-binding --set clusterrole.serviceaccount.name=$USERNAME --set clusterrole.secret.name=$USERNAME
    else
        helm upgrade $USERNAME --install roles/ --dry-run \
        --set role.namespace=$NAMESPACE --set role.name=developer-role --set rolebinding.name=developer-role-binding--set role.serviceaccount.name=$USERNAME --set role.secret.name=$USERNAME
    fi
}


apply() {
    if [ $ROLE == "ClusterRole" ]; then
        helm upgrade $USERNAME --install roles/ \
        --set clusterrole.name=clusterrole --set clusterrolebinding.name=clusterrole-binding --set clusterrole.serviceaccount.name=$USERNAME --set clusterrole.secret.name=$USERNAME
    else
        helm upgrade $USERNAME --install roles/ \
        --set role.namespace=$NAMESPACE --set role.name=developer-role --set rolebinding.name=developer-role-binding --set role.serviceaccount.name=$USERNAME --set role.secret.name=$USERNAME
    fi
}
if [ $ACTION == "plan" ]; then
  plan
elif [ $ACTION == "apply" ]; then
  apply
else
  echo "Wrong Option !!"
fi
</code></pre>
<p>This bash script serves to deploy RBAC configurations to Kubernetes clusters based on provided parameters. It starts by setting the necessary variables and then defines two functions, <code>plan</code> and <code>apply</code>, to handle the Helm chart deployment in dry-run mode and actual application mode, respectively. The Helm chart creates the following Kubernetes resources:</p>
<ul>
<li><p>Role/ClusterRole</p>
</li>
<li><p>RoleBinding/ClusterRoleBinding</p>
</li>
<li><p>ServiceAccount</p>
</li>
<li><p>Secret</p>
</li>
</ul>
<p>The Secret is bound to the ServiceAccount to store the ServiceAccount token, which serves as a bearer token for accessing the cluster. So which means we are accessing the cluster using <strong>Bearer Token</strong> method. Here, we have created the secret but it can also be kept in a file and mounted from a volume mount and the path can be provided as client’s key. Also, to make sure that service account tokens do not expire from Kubernetes V1.24 secrets are bound with service account and do not have a expiry(i.e not time bound). However we have not used the TokenSecretAPI to create a token. After the helm chart is deployed we move to the kubeconfig generation part which is then sent via email to the user. I wanted to explain about the apiGroups, Resources and Verbs that have been used on the helm charts but explain it would make this article very long and also kubernetes documentation has explained it properly.</p>
<p>Now comes the kubeconfig.yaml generation part</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-built_in">set</span> -xe

ROLE=<span class="hljs-variable">$ROLE</span>
MASTER_IP=<span class="hljs-variable">$MASTER_IP</span>
USERNAME=<span class="hljs-variable">$USERNAME</span>
NAMESPACE=<span class="hljs-variable">$NAMESPACE</span>
<span class="hljs-built_in">export</span> KUBECONFIG=kubeconfig.yaml

<span class="hljs-function"><span class="hljs-title">token_clusterrole</span></span>(){
  USER_TOKEN=$(kubectl describe secrets <span class="hljs-string">"<span class="hljs-variable">$USERNAME</span>"</span> -n kube-system | awk <span class="hljs-string">'/token:/ {print $2}'</span>)
}
<span class="hljs-function"><span class="hljs-title">token_role</span></span>() {
  USER_TOKEN=$(kubectl describe secrets <span class="hljs-string">"<span class="hljs-variable">$USERNAME</span>"</span> -n <span class="hljs-string">"<span class="hljs-variable">$NAMESPACE</span>"</span> | awk <span class="hljs-string">'/token:/ {print $2}'</span>)
}
<span class="hljs-function"><span class="hljs-title">generate_kubeconfig</span></span>() {
CERTIFICATE=$(kubectl config view --flatten --minify=<span class="hljs-literal">true</span> -o=jsonpath=<span class="hljs-string">'{.clusters[].cluster.certificate-authority-data}'</span>)
    cat &lt;&lt;EOF &gt; kubeconfig_user.yaml
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: <span class="hljs-variable">$CERTIFICATE</span>
    server: https://<span class="hljs-variable">$MASTER_IP</span>:6443 <span class="hljs-comment">#clusterendpoint</span>
  name: <span class="hljs-variable">$MASTER_IP</span> <span class="hljs-comment">#clustername</span>
contexts:
- context:
    cluster: <span class="hljs-variable">$MASTER_IP</span> <span class="hljs-comment">#clustername</span>
    user: <span class="hljs-variable">$USERNAME</span> <span class="hljs-comment">#service-account</span>
  name: default <span class="hljs-comment">#clustername</span>
current-context: default
kind: Config
users:
- name: <span class="hljs-variable">$USERNAME</span> <span class="hljs-comment">#service-account</span>
  user:
    token: <span class="hljs-variable">$USER_TOKEN</span>
EOF

    <span class="hljs-built_in">echo</span> <span class="hljs-string">"kubeconfig file generated successfully!"</span>
}

<span class="hljs-keyword">if</span> [ <span class="hljs-variable">$ROLE</span> == <span class="hljs-string">"ClusterRole"</span> ]; <span class="hljs-keyword">then</span>
  token_clusterrole
<span class="hljs-keyword">else</span>
  token_role
<span class="hljs-keyword">fi</span>
generate_kubeconfig
</code></pre>
<p>This bash script is responsible for generating a kubeconfig file that facilitates user authentication with the Kubernetes cluster. It begins by setting variables and exporting the path to the kubeconfig file.</p>
<p>The <code>generate_kubeconfig</code> function constructs the kubeconfig file using the retrieved user token and the cluster's certificate authority data. This certificate is crucial for establishing a secure connection to the cluster's API server. Additionally, the script sets the context to 'default,' indicating the default configuration for interacting with the cluster.</p>
<p>In summary, this script automates the generation of a kubeconfig file, ensuring secure user authentication and access to Kubernetes cluster resources. It incorporates the user’s token and the cluster’s certificate authority data into the configuration, establishing a secure and authenticated connection for cluster interactions. The default context simplifies cluster interaction by providing a predefined configuration for the user.<br />Like above we can create a kubeconfig file with multiple context which will allow us to switch between the context using below given command but this is only an example for a single context.</p>
<pre><code class="lang-plaintext">kubectl config use-context context_name
</code></pre>
<p>Now the kubeconfig file has been created. The admin who created the kubeconfig file can test the authentication and authorization by using commands given as examples below:</p>
<pre><code class="lang-plaintext">kubectl auth can-i list pods --namespace namespace --as system:serviceaccount:namespace:serviceaccountname
kubectl auth can-i create pods --as username
</code></pre>
<p>Please leave some comments if this article has helped you and highlight if there is something that needs to be improved.</p>
]]></content:encoded></item><item><title><![CDATA[Centralized Storage with Amazon EFS in an Autoscaling Environment with Ansible]]></title><description><![CDATA[In today’s dynamic cloud infrastructure, the need to scale resources seamlessly to handle varying workloads is paramount. Autoscaling groups in AWS provide a solution to dynamically adjust the number of EC2 instances based on demand. However, managin...]]></description><link>https://khalti.engineering/centralized-storage-with-amazon-efs-in-an-autoscaling-environment-with-ansible</link><guid isPermaLink="true">https://khalti.engineering/centralized-storage-with-amazon-efs-in-an-autoscaling-environment-with-ansible</guid><category><![CDATA[Infrastructure as code]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Devops articles]]></category><category><![CDATA[AWS]]></category><category><![CDATA[autoscaling]]></category><category><![CDATA[#Terraform #AWS #InfrastructureAsCode #Provisioning #Automation #CloudComputing]]></category><dc:creator><![CDATA[Aman Maharjan]]></dc:creator><pubDate>Tue, 30 Jan 2024 10:49:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706635234410/05307b5a-0558-4799-9727-8f4c9ca4c1fd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today’s dynamic cloud infrastructure, the need to scale resources seamlessly to handle varying workloads is paramount. Autoscaling groups in AWS provide a solution to dynamically adjust the number of EC2 instances based on demand. However, managing the storage of ephemeral instances can pose challenges, especially when dealing with logs and other persistent files.</p>
<h1 id="heading-the-power-of-autoscaling-groups"><strong>The Power of Autoscaling Groups</strong></h1>
<p>To address the demands of growing traffic in applications and businesses, the implementation of autoscaling groups becomes crucial. Autoscaling allows you to define scaling policies based on metrics like CPU utilization or network traffic, ensuring your application can handle increased load without manual intervention.</p>
<h1 id="heading-building-a-golden-image-with-packer-and-ansible"><strong>Building a Golden Image with Packer and Ansible</strong></h1>
<p>My choice for implementing autoscaling of EC2 instances involves creating a golden image using Packer. Packer, in combination with Ansible as the provisioner, allows me to build an Amazon Machine Image (AMI) that contains all the necessary requirements and dependencies for my application. This golden image serves as the foundation for the instances launched by the autoscaling group.</p>
<p>Here’s a snippet of the Packer template (template.json):</p>
<pre><code class="lang-json"><span class="hljs-comment">// ... (Previous Packer configuration)</span>

<span class="hljs-string">"provisioners"</span>: [
    {
        <span class="hljs-attr">"type"</span>: <span class="hljs-string">"shell"</span>,
        <span class="hljs-attr">"script"</span>: <span class="hljs-string">"/tmp/init.sh"</span>
    },
    {
        <span class="hljs-attr">"type"</span>: <span class="hljs-string">"shell"</span>,
        <span class="hljs-attr">"inline"</span>: [
            <span class="hljs-string">"sleep 30"</span>,
            <span class="hljs-string">"df -h"</span>,
            <span class="hljs-string">"lsblk -o NAME,FSTYPE /dev/nvme1n1"</span>
        ]
    },
    {
        <span class="hljs-attr">"type"</span>: <span class="hljs-string">"ansible"</span>,
        <span class="hljs-attr">"galaxy_file"</span>: <span class="hljs-string">"{{user `ansible_dir`}}/ansible/requirements.yml"</span>,
        <span class="hljs-attr">"playbook_file"</span>: <span class="hljs-string">"{{user `ansible_dir`}}/ansible/ansible/playbooks/configure.yaml"</span>,
        <span class="hljs-attr">"extra_arguments"</span>: [<span class="hljs-string">"-v"</span>,<span class="hljs-string">"--extra-vars"</span>, <span class="hljs-string">"artifact_path={{ user `project_path` }} EFS_DNS_NAME={{ user `efs_dns_name` }} EFS_MOUNT_TARGET_IP={{ user `efs_mount_target_ip` }}"</span>],
        <span class="hljs-attr">"user"</span>: <span class="hljs-string">"{{user `ansible_remote_user`}}"</span>
    }
],

<span class="hljs-comment">// ... (Subsequent Packer configuration)</span>
</code></pre>
<p>In this template, I’m using Ansible to configure the EC2 instance with the necessary settings. Additionally, I’m passing variables related to the Amazon EFS setup, such as DNS name and mount target IP, to the Ansible playbook.</p>
<h1 id="heading-centralized-storage-with-amazon-efs"><strong>Centralized Storage with Amazon EFS</strong></h1>
<p>When running multiple dynamic instances from an auto-scaling group, the logs generated in each instance are usually stored in the local storage of that instance. However, with auto-scaling, instances may come and go, leading to potential data loss. This is where a centralized storage solution becomes essential.</p>
<p>In scenarios where central logging solutions such as ELK, cloud-provided options like CloudWatch, or third-party solutions like Datadog are not utilized, leveraging Amazon Elastic File System (EFS) for log storage emerges as a cost-effective and efficient alternative. By storing logs in EFS, we create a shared repository accessible by dynamic instances within an autoscaling environment. This not only ensures persistence across instances but also significantly reduces costs compared to alternative solutions. Moreover, the simplicity of utilizing bash tools for parsing logs in a Linux server further enhances the practicality of this implementation, making it an attractive choice for environments where centralized logging platforms might be overkill or cost-prohibitive.</p>
<h1 id="heading-amazon-efs-to-the-rescue"><strong>Amazon EFS to the Rescue</strong></h1>
<p>Amazon Elastic File System (EFS) provides scalable and shared file storage that can be mounted on multiple EC2 instances. This makes EFS an ideal solution for storing logs and other files that need to persist across instances.</p>
<h1 id="heading-ansible-role-for-efs-configuration"><strong>Ansible Role for EFS Configuration</strong></h1>
<p>To facilitate the configuration of EFS on EC2 instances, I’ve created an Ansible role named "efs". This role ensures the necessary dependencies are installed, clones the amazon-efs-utils from GitHub, builds the required deb packages, installs them on the instances, and finally mounts the EFS volume.</p>
<p>Here’s a snippet of the Ansible role (tasks/main.yaml):</p>
<pre><code class="lang-yaml"><span class="hljs-string">//</span> <span class="hljs-string">…</span> <span class="hljs-string">(Previous</span> <span class="hljs-string">Ansible</span> <span class="hljs-string">tasks)</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Update</span> <span class="hljs-string">repositories</span> <span class="hljs-string">for</span> <span class="hljs-string">EFS</span> <span class="hljs-string">packages</span>
  <span class="hljs-attr">apt:</span>
    <span class="hljs-attr">update_cache:</span> <span class="hljs-literal">yes</span>
    <span class="hljs-attr">upgrade:</span> <span class="hljs-string">dist</span>
    <span class="hljs-attr">state:</span> <span class="hljs-string">latest</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Make</span> <span class="hljs-string">sure</span> <span class="hljs-string">the</span> <span class="hljs-string">efs</span> <span class="hljs-string">dependency</span> <span class="hljs-string">packages</span> <span class="hljs-string">are</span> <span class="hljs-string">installed</span> <span class="hljs-string">(Debian/Ubuntu)</span>
  <span class="hljs-attr">apt:</span>
    <span class="hljs-attr">pkg:</span> <span class="hljs-string">"<span class="hljs-template-variable">{{item}}</span>"</span>
    <span class="hljs-attr">state:</span> <span class="hljs-string">present</span>
    <span class="hljs-attr">update_cache:</span> <span class="hljs-literal">yes</span>
  <span class="hljs-attr">with_items:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">git</span>
    <span class="hljs-bullet">-</span> <span class="hljs-string">binutils</span>
  <span class="hljs-attr">when:</span> <span class="hljs-string">ansible_distribution</span> <span class="hljs-string">in</span> [ <span class="hljs-string">"Debian"</span>, <span class="hljs-string">"Ubuntu"</span> ]

<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Clone</span> <span class="hljs-string">amazon-efs-utils</span> <span class="hljs-string">from</span> <span class="hljs-string">GitHub</span> 
  <span class="hljs-attr">ansible.builtin.git:</span>
    <span class="hljs-attr">repo:</span> <span class="hljs-string">"https://github.com/aws/efs-utils"</span>
    <span class="hljs-attr">dest:</span> <span class="hljs-string">"/tmp/efs-utils"</span>
    <span class="hljs-attr">update:</span> <span class="hljs-literal">true</span>
    <span class="hljs-attr">version:</span> <span class="hljs-string">"master"</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Build</span> <span class="hljs-string">deb</span> <span class="hljs-string">packages</span> <span class="hljs-string">from</span> <span class="hljs-string">the</span> <span class="hljs-string">aws/efs-utils</span> <span class="hljs-string">code</span>
  <span class="hljs-attr">ansible.builtin.command:</span> <span class="hljs-string">./build-deb.sh</span>
  <span class="hljs-attr">args:</span>
    <span class="hljs-attr">chdir:</span> <span class="hljs-string">/tmp/efs-utils</span>
    <span class="hljs-attr">creates:</span> <span class="hljs-string">/tmp/efs-utils/build</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Find</span> <span class="hljs-string">all</span> <span class="hljs-string">aws/efs-utils</span> <span class="hljs-string">deb</span> <span class="hljs-string">packages</span> <span class="hljs-string">that</span> <span class="hljs-string">were</span> <span class="hljs-string">built</span>
  <span class="hljs-attr">ansible.builtin.find:</span>
    <span class="hljs-attr">paths:</span> <span class="hljs-string">/tmp/efs-utils/build</span>
    <span class="hljs-attr">patterns:</span> <span class="hljs-string">"amazon-efs-utils*.deb"</span>
  <span class="hljs-attr">register:</span> <span class="hljs-string">find_result</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Install</span> <span class="hljs-string">aws/efs-utils</span> <span class="hljs-string">deb</span> <span class="hljs-string">packages</span>
  <span class="hljs-attr">ansible.builtin.apt:</span>
    <span class="hljs-attr">deb:</span> <span class="hljs-string">"<span class="hljs-template-variable">{{ item }}</span>"</span>
  <span class="hljs-attr">loop:</span> <span class="hljs-string">"<span class="hljs-template-variable">{{ find_result | json_query('files[*].path') }}</span>"</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Create</span> <span class="hljs-string">mount</span> <span class="hljs-string">point</span> <span class="hljs-string">directory</span>
  <span class="hljs-attr">file:</span>
    <span class="hljs-attr">path:</span> <span class="hljs-string">/efslogs</span>
    <span class="hljs-attr">state:</span> <span class="hljs-string">directory</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Mount</span> <span class="hljs-string">EFS</span> <span class="hljs-string">volume</span>
  <span class="hljs-attr">mount:</span>
    <span class="hljs-attr">path:</span> <span class="hljs-string">/efslogs</span>
    <span class="hljs-attr">src:</span> <span class="hljs-string">"<span class="hljs-template-variable">{{EFS_DNS_NAME}}</span>:/"</span>
    <span class="hljs-attr">fstype:</span> <span class="hljs-string">efs</span>
    <span class="hljs-attr">opts:</span> <span class="hljs-string">"tls,mounttargetip=<span class="hljs-template-variable">{{EFS_MOUNT_TARGET_IP}}</span>"</span>
    <span class="hljs-attr">state:</span> <span class="hljs-string">mounted</span>
</code></pre>
<p>In this role, I’m using Ansible to perform tasks such as updating repositories, installing dependencies, cloning the amazon-efs-utils from GitHub, building and installing deb packages, creating a mount point directory, and finally, mounting the EFS volume.</p>
<p>The CodeBuild builder instance should be able to contact the mount target created during EFS provisioning. In most cases, public subnets are used for the builder instance in CodeBuild, while the service nodes, which run in an autoscaling group, are placed in private subnets. For this scenario, it is recommended to create mount targets in EFS exclusively for private subnets. Due to the builder instance in CodeBuild being unable to reach the mount target, the Ansible task for mounting the EFS volume may not work as intended. In such cases, it is advisable to exclude that task from the Ansible role and instead incorporate the mount script into the EC2 init script.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Mount EFS</span>
findmnt --mountpoint /efs
<span class="hljs-keyword">if</span> [ $? -ne 0 ]; <span class="hljs-keyword">then</span>
  mount -t efs -o tls,mounttargetip=<span class="hljs-variable">${efs_mount_target_ip}</span> <span class="hljs-variable">${efs_filesystem_id}</span> /efs/
<span class="hljs-keyword">else</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"EFS filesystem is already mounted"</span>
<span class="hljs-keyword">fi</span>
</code></pre>
<h1 id="heading-terraform-orchestration-for-amazon-efs-provisioning"><strong>Terraform Orchestration for Amazon EFS Provisioning</strong></h1>
<p>In conjunction with the robust Packer and Ansible setup for creating a golden EC2 image, the Terraform implementation adds another layer of sophistication to infrastructure orchestration. This Terraform script focuses on provisioning Amazon Elastic File System (EFS), offering a centralized and scalable solution for shared file storage. The script elegantly encapsulates various aspects of EFS configuration, including file system parameters, lifecycle policies, security groups, access points, and replication configurations. The modular structure of the script ensures adaptability, allowing seamless integration with existing infrastructure components. Leveraging the Terraform VPC module further enhances the overall network layout, establishing a resilient foundation for the EFS deployment. The inclusion of a customer-managed KMS key ensures data security through encryption. Altogether, this Terraform implementation, when combined with the earlier Packer and Ansible components, presents a comprehensive and automated approach to deploying, configuring, and managing EFS in an AWS environment.</p>
<p>Here’s a snippet of the Terraform:</p>
<pre><code class="lang-ini">provider "aws" {
  <span class="hljs-attr">region</span> = local.region
}

locals {
  <span class="hljs-attr">region</span> = <span class="hljs-string">"ap-south-1"</span>
  <span class="hljs-attr">name</span>   = <span class="hljs-string">"ex-${basename(path.cwd)}"</span>

  <span class="hljs-attr">azs</span> = slice(data.aws_availability_zones.available.names, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>)

  <span class="hljs-attr">tags</span> = {
    <span class="hljs-attr">Name</span>       = local.name
    <span class="hljs-attr">Example</span>    = local.name
    <span class="hljs-attr">Repository</span> = <span class="hljs-string">"https://github.com/terraform-aws-modules/terraform-aws-efs"</span>
  }
}

data "aws_availability_zones" "available" {}
data "aws_caller_identity" "current" {}

<span class="hljs-comment">################################################################################</span>
<span class="hljs-comment"># EFS Module</span>
<span class="hljs-comment">################################################################################</span>

module "efs" {
  <span class="hljs-attr">source</span> = <span class="hljs-string">"../.."</span>

  <span class="hljs-comment"># File system</span>
  <span class="hljs-attr">name</span>           = local.name
  <span class="hljs-attr">creation_token</span> = local.name
  <span class="hljs-attr">encrypted</span>      = <span class="hljs-literal">true</span>
  <span class="hljs-attr">kms_key_arn</span>    = module.kms.key_arn

  <span class="hljs-attr">performance_mode</span>                = <span class="hljs-string">"maxIO"</span>
  <span class="hljs-attr">throughput_mode</span>                 = <span class="hljs-string">"provisioned"</span>
  <span class="hljs-attr">provisioned_throughput_in_mibps</span> = <span class="hljs-number">256</span>

  <span class="hljs-attr">lifecycle_policy</span> = {
    <span class="hljs-attr">transition_to_ia</span>                    = <span class="hljs-string">"AFTER_30_DAYS"</span>
    <span class="hljs-attr">transition_to_primary_storage_class</span> = <span class="hljs-string">"AFTER_1_ACCESS"</span>
  }

  <span class="hljs-comment"># File system policy</span>
  <span class="hljs-attr">attach_policy</span>                      = <span class="hljs-literal">true</span>
  <span class="hljs-attr">bypass_policy_lockout_safety_check</span> = <span class="hljs-literal">false</span>
  <span class="hljs-attr">policy_statements</span> = [
    {
      sid     = <span class="hljs-string">"Example"</span>
      actions = [<span class="hljs-string">"elasticfilesystem:ClientMount"</span>]
      principals = [
        {
          type        = <span class="hljs-string">"AWS"</span>
          identifiers = [data.aws_caller_identity.current.arn]
        }
      ]
    }
  ]

  <span class="hljs-comment"># Mount targets / security group</span>
  <span class="hljs-attr">mount_targets</span>              = { for k, v in zipmap(local.azs, module.vpc.private_subnets) : k =&gt; { subnet_id = v } }
  <span class="hljs-attr">security_group_description</span> = <span class="hljs-string">"Example EFS security group"</span>
  <span class="hljs-attr">security_group_vpc_id</span>      = module.vpc.vpc_id
  <span class="hljs-attr">security_group_rules</span> = {
    <span class="hljs-attr">vpc</span> = {
      <span class="hljs-comment"># relying on the defaults provdied for EFS/NFS (2049/TCP + ingress)</span>
      <span class="hljs-attr">description</span> = <span class="hljs-string">"NFS ingress from VPC private subnets"</span>
      <span class="hljs-attr">cidr_blocks</span> = module.vpc.private_subnets_cidr_blocks
    }
  }

  <span class="hljs-comment"># Access point(s)</span>
  <span class="hljs-attr">access_points</span> = {
    <span class="hljs-attr">posix_example</span> = {
      <span class="hljs-attr">name</span> = <span class="hljs-string">"posix-example"</span>
      <span class="hljs-attr">posix_user</span> = {
        <span class="hljs-attr">gid</span>            = <span class="hljs-number">1001</span>
        <span class="hljs-attr">uid</span>            = <span class="hljs-number">1001</span>
        <span class="hljs-attr">secondary_gids</span> = [<span class="hljs-number">1002</span>]
      }

      <span class="hljs-attr">tags</span> = {
        <span class="hljs-attr">Additionl</span> = <span class="hljs-string">"yes"</span>
      }
    }
    <span class="hljs-attr">root_example</span> = {
      <span class="hljs-attr">root_directory</span> = {
        <span class="hljs-attr">path</span> = <span class="hljs-string">"/example"</span>
        <span class="hljs-attr">creation_info</span> = {
          <span class="hljs-attr">owner_gid</span>   = <span class="hljs-number">1001</span>
          <span class="hljs-attr">owner_uid</span>   = <span class="hljs-number">1001</span>
          <span class="hljs-attr">permissions</span> = <span class="hljs-string">"755"</span>
        }
      }
    }
  }

  <span class="hljs-comment"># Backup policy</span>
  <span class="hljs-attr">enable_backup_policy</span> = <span class="hljs-literal">true</span>

  <span class="hljs-comment"># Replication configuration</span>
  <span class="hljs-attr">create_replication_configuration</span> = <span class="hljs-literal">true</span>
  <span class="hljs-attr">replication_configuration_destination</span> = {
    <span class="hljs-attr">region</span> = <span class="hljs-string">"eu-west-2"</span>
  }

  <span class="hljs-attr">tags</span> = local.tags
}


<span class="hljs-comment">################################################################################</span>
<span class="hljs-comment"># Supporting Resources</span>
<span class="hljs-comment">################################################################################</span>

module "vpc" {
  <span class="hljs-attr">source</span>  = <span class="hljs-string">"terraform-aws-modules/vpc/aws"</span>
  <span class="hljs-attr">version</span> = <span class="hljs-string">"~&gt; 5.0"</span>

  <span class="hljs-attr">name</span> = local.name
  <span class="hljs-attr">cidr</span> = <span class="hljs-string">"10.99.0.0/18"</span>

  <span class="hljs-attr">azs</span>             = local.azs
  <span class="hljs-attr">public_subnets</span>  = [<span class="hljs-string">"10.0.1.0/24"</span>, <span class="hljs-string">"10.0.2.0/24"</span>, <span class="hljs-string">"10.0.3.0/24"</span>]
  <span class="hljs-attr">private_subnets</span> = [<span class="hljs-string">"10.0.4.0/24"</span>, <span class="hljs-string">"10.0.5.0/24"</span>, <span class="hljs-string">"10.0.6.0/24"</span>]

  <span class="hljs-attr">enable_nat_gateway</span> = <span class="hljs-literal">false</span>
  <span class="hljs-attr">single_nat_gateway</span> = <span class="hljs-literal">true</span>

  <span class="hljs-attr">tags</span> = local.tags
}

module "kms" {
  <span class="hljs-attr">source</span>  = <span class="hljs-string">"terraform-aws-modules/kms/aws"</span>
  <span class="hljs-attr">version</span> = <span class="hljs-string">"~&gt; 1.0"</span>

  <span class="hljs-attr">aliases</span>               = [<span class="hljs-string">"efs/${local.name}"</span>]
  <span class="hljs-attr">description</span>           = <span class="hljs-string">"EFS customer managed key"</span>
  <span class="hljs-attr">enable_default_policy</span> = <span class="hljs-literal">true</span>

  <span class="hljs-comment"># For example use only</span>
  <span class="hljs-attr">deletion_window_in_days</span> = <span class="hljs-number">7</span>

  <span class="hljs-attr">tags</span> = local.tags
}
</code></pre>
<h1 id="heading-putting-it-all-together"><strong>Putting It All Together</strong></h1>
<ul>
<li><p><strong>Golden Image Creation</strong>: The process starts with creating a golden image using Packer. This image includes the necessary configurations and dependencies for the application.</p>
</li>
<li><p><strong>Autoscaling with Terraform</strong>: Terraform is then used to deploy the AMI to the autoscaling group. This ensures that the environment scales seamlessly based on specified criteria, meeting the demands of varying traffic.</p>
</li>
<li><p><strong>Centralized Storage with EFS</strong>: Ephemeral EC2 instances often result in data loss. By employing Amazon EFS, storage is centralized, providing persistence for logs and other essential files. This is particularly valuable when central logging solutions like ELK or cloud-provided solutions are not used.</p>
</li>
</ul>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>In conclusion, the implemented solution offers a cost-effective and scalable approach to managing EC2 instances in an autoscaling group. The combination of Packer, Ansible, Terraform, and Amazon EFS provides automation, ease of deployment, and persistent storage, addressing the challenges associated with dynamic environments.</p>
<p>By centralizing storage with EFS, data continuity is ensured even when instances are dynamically added or removed. This implementation serves as a robust foundation for handling varying workloads, supporting the growth of applications, and optimizing infrastructure resources.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">also published at <a target="_blank" href="https://medium.com/@mhrznamn068/centralized-storage-with-amazon-efs-in-an-autoscaling-environment-d00be8007d79">medium</a> on the author's blog.</div>
</div>]]></content:encoded></item><item><title><![CDATA[Chapter 05 - Shipping Fintech at Scale]]></title><description><![CDATA[This chapter mainly focuses on strategies for packaging and deployment in large-scale applications, taking into account the needs for high throughput and integrity. It includes eleven topics, each with its dedicated chapter page that delves into the ...]]></description><link>https://khalti.engineering/chapter-05-shipping-fintech-at-scale</link><guid isPermaLink="true">https://khalti.engineering/chapter-05-shipping-fintech-at-scale</guid><dc:creator><![CDATA[Aman Maharjan]]></dc:creator><pubDate>Thu, 04 Jan 2024 09:48:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/4aOhA4ptIY4/upload/7b0f6fd2b67a3668af689e2702990374.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This chapter mainly focuses on strategies for packaging and deployment in large-scale applications, taking into account the needs for high throughput and integrity. It includes eleven topics, each with its dedicated chapter page that delves into the specifics.</p>
<ol>
<li><p>Packaging</p>
</li>
<li><p>Configuration Management and IaC</p>
</li>
<li><p><a target="_blank" href="https://khalti.engineering/fintech-engineering-chapter-05-03-deployment-strategies">Deployment Strategies</a></p>
</li>
<li><p>Scalability Considerations</p>
</li>
<li><p>SDLC Automation</p>
</li>
<li><p>Release Management</p>
</li>
<li><p>Database</p>
</li>
<li><p>Reliability Engineering</p>
</li>
<li><p>Cloud and On-Premise Deployments</p>
</li>
<li><p>Security Challenges and Implementation</p>
</li>
<li><p>Regulatory compliance and data protection in the Fintech industry</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Chapter 05 - 03 - Deployment Strategies]]></title><description><![CDATA[Rolling deployments and zero-downtime releases

Blue-green deployments and canary releases

Deployment automation pipelines]]></description><link>https://khalti.engineering/fintech-engineering-chapter-05-03-deployment-strategies</link><guid isPermaLink="true">https://khalti.engineering/fintech-engineering-chapter-05-03-deployment-strategies</guid><dc:creator><![CDATA[Aman Maharjan]]></dc:creator><pubDate>Thu, 04 Jan 2024 09:45:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/knfWGDje7cs/upload/a82ea4c0019b63269d98f095f7f7d3fd.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<ul>
<li><p>Rolling deployments and zero-downtime releases</p>
</li>
<li><p>Blue-green deployments and canary releases</p>
</li>
<li><p>Deployment automation pipelines</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Chapter 01 - Applied Fintech Engineering]]></title><description><![CDATA[Regulatory Framework

Office of Company Registrar (OCR): Manages company registrations, ensuring legal compliance for incorporation, regular updates and change of control records, etc.

Inland Revenue Department (IRD): In Nepal, the Inland Revenue De...]]></description><link>https://khalti.engineering/chapter-01-applied-fintech-engineering</link><guid isPermaLink="true">https://khalti.engineering/chapter-01-applied-fintech-engineering</guid><category><![CDATA[ioe-elective]]></category><category><![CDATA[applied-fintech-engineering]]></category><category><![CDATA[courseware]]></category><dc:creator><![CDATA[Dhruba Adhikari]]></dc:creator><pubDate>Sun, 31 Dec 2023 18:57:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/2_K82gx9Uk8/upload/87708d38269b831bfce1721180daa717.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-regulatory-framework"><strong>Regulatory Framework</strong></h3>
<ul>
<li><p><strong>Office of Company Registrar (OCR):</strong> Manages company registrations, ensuring legal compliance for incorporation, regular updates and change of control records, etc.</p>
</li>
<li><p><strong>Inland Revenue Department (IRD):</strong> In Nepal, the Inland Revenue Department (IRD) is primarily responsible for the administration and collection of various taxes. Their main functions include:</p>
<ol>
<li><p><strong>Tax Collection:</strong> The IRD is responsible for collecting a range of taxes, including income tax, Value Added Tax (VAT), excise duties, and other internal taxes.</p>
</li>
<li><p><strong>Tax Policy Implementation:</strong> Implementing and enforcing tax policies set forth by the government. This includes ensuring compliance with tax laws and regulations.</p>
</li>
<li><p><strong>Taxpayer Services:</strong> Providing services to taxpayers, such as processing tax returns, issuing tax refunds, and offering guidance on tax-related matters.</p>
</li>
<li><p><strong>Tax Compliance and Enforcement:</strong> Monitoring and ensuring compliance with tax laws. This includes conducting audits and investigations into tax evasion or fraud.</p>
</li>
<li><p><strong>Policy Development and Reform:</strong> The IRD also plays a role in developing tax policy and proposing reforms to improve the tax system.</p>
</li>
<li><p><strong>International Tax Affairs:</strong> Managing international tax matters, including the implementation of tax treaties and handling cross-border tax issues.</p>
</li>
</ol>
</li>
<li><p><strong>Nepal Rastra Bank (NRB), Payment System Department:</strong> Among several regulatory activities performed by NRB, it primarily looks into the following areas of the payment systems -</p>
<ul>
<li><p><strong>Regulation and Supervision:</strong> NRB regulates and supervises Nepal's payment systems, ensuring their smooth and secure operation.</p>
</li>
<li><p><strong>System Development and Modernization:</strong> The bank is responsible for upgrading and modernizing payment system infrastructure, incorporating new technologies for efficiency and security.</p>
</li>
<li><p><strong>Policy Formulation:</strong> NRB formulates policies for the operation and management of payment systems, setting standards and guidelines to govern these systems.</p>
</li>
<li><p><strong>Promotion of Electronic Payments:</strong> The department actively promotes electronic payment methods to reduce cash reliance and enhance transaction efficiency.</p>
</li>
<li><p><strong>Risk Management:</strong> It identifies and manages risks in payment systems, focusing on operational, settlement, and systemic risks.</p>
</li>
<li><p><strong>International Collaboration:</strong> NRB engages in international collaborations to align with global best practices in payment systems.</p>
</li>
</ul>
</li>
</ul>
<p>    In essence, the NRB's Payment System Department is pivotal in maintaining the integrity, efficiency, and stability of Nepal's financial transaction systems.</p>
<ul>
<li><p><strong>Department of National ID and Civil Registration:</strong> Integrates national ID systems with fintech, enhancing KYC processes.</p>
</li>
<li><p>Monetary Policy, etc</p>
</li>
<li><p>Department of National ID and Civil Registration (National ID)</p>
</li>
<li><p>The Journey of Khalti</p>
</li>
<li><p>E-Commerce Act in Nepal, Electronic Transaction and Transfer Act</p>
</li>
</ul>
<h3 id="heading-industry-landscape"><strong>Industry Landscape</strong></h3>
<p><strong>The types of Banking</strong></p>
<ul>
<li><p><strong>Brick and Mortar Banking -</strong> refers to traditional banking services offered through physical branch locations. This primarily includes services around Physical Branches, In-Person services, Physical verification, Deposit Lockers, etc.</p>
</li>
<li><p><strong>Digital Banking</strong> - Digital Banking is an extension of a brick and mortar banking, providing access to the banking through digital channels and offerings - such as funds transfer, bill payments, account management, and loan applications, typically through a website or mobile app.</p>
</li>
<li><p><strong>Neo Banking</strong> - Neo Banking represents a more radical shift from traditional banking. Neo banks are fintech firms that operate exclusively online and do not have any physical branches. Key features include:</p>
</li>
</ul>
<p><strong>Other Industry components</strong></p>
<ul>
<li><p><strong>BFIs</strong> - Banking and Financial Institutions</p>
</li>
<li><p><strong>PSO</strong> - Payment services operator</p>
</li>
<li><p><strong>PSP</strong> - Payment services provider</p>
</li>
<li><p><strong>Digital Wallets -</strong></p>
</li>
</ul>
<p><strong>Nearby Markets and Crossborder payments</strong></p>
<p><mark>(some literature missing...)</mark></p>
<ul>
<li><p>UPI India</p>
</li>
<li><p>Remittance</p>
</li>
<li><p>Cross Border Payments</p>
</li>
<li><p>Visa, MasterCard, EMVCo</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[[Curriculum] Applied Fintech Engineering]]></title><description><![CDATA[The objective of this course is to understand the fundamentals of Fintech industry, develop technical skills for building Fintech solutions thus cultivating a business mindset to solve real-world problems.
Course Outcomes
Students will gain a good gr...]]></description><link>https://khalti.engineering/applied-fintech-engineering-ioe-elective</link><guid isPermaLink="true">https://khalti.engineering/applied-fintech-engineering-ioe-elective</guid><category><![CDATA[ioe-elective]]></category><category><![CDATA[academic-partnership]]></category><category><![CDATA[applied-fintech-engineering]]></category><category><![CDATA[pulchowk-campus]]></category><category><![CDATA[Tribhuvan University]]></category><dc:creator><![CDATA[Dhruba Adhikari]]></dc:creator><pubDate>Sun, 31 Dec 2023 18:32:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/EKy2OTRPXdw/upload/fb9cf91eb2d96760add797438c3a9903.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The objective of this course is to understand the fundamentals of Fintech industry, develop technical skills for building Fintech solutions thus cultivating a business mindset to solve real-world problems.</p>
<h2 id="heading-course-outcomes"><strong>Course Outcomes</strong></h2>
<p>Students will gain a good grasp of the basics in the Fintech industry, understanding how it works. They'll explore various career paths within fintech, from creating new solutions to making them available for people to using them on a larger scale. Additionally, they'll develop reasoning skills to help them choose which specific areas of fintech they're most interested in.</p>
<p>Moreover, students will collaborate with one of the successful fintech companies in the country, gaining first hand experience of how things operate in the real world. This practical engagement will provide them with insights into the actual workings of the industry, offering valuable exposure beyond theoretical knowledge.</p>
<h2 id="heading-course-details"><strong>Course Details</strong></h2>
<ol>
<li><p>Fintech in Nepal</p>
<ol>
<li><p>Regulatory Framework</p>
<ol>
<li><p>OCR</p>
</li>
<li><p>IRD</p>
</li>
<li><p>NRB(Payment System Department), Monetary Policy, etc</p>
</li>
<li><p>Department of National ID and Civil Registration (National ID)</p>
</li>
<li><p>The Journey of Khalti</p>
</li>
<li><p>E-Commerce Act in Nepal, Electronic Transaction and Transfer Act</p>
</li>
</ol>
</li>
<li><p>Industry Landscape</p>
<ol>
<li><p>Brick and Mortar Banking</p>
</li>
<li><p>BFIs</p>
</li>
<li><p>PSO</p>
</li>
<li><p>PSP</p>
</li>
<li><p>Digital Wallets</p>
</li>
<li><p>Nearby Markets</p>
</li>
<li><p>Cross Border Payments</p>
</li>
<li><p>UPI India</p>
</li>
<li><p>Visa, MasterCard, EMVCo</p>
</li>
</ol>
</li>
</ol>
</li>
<li><p>Fintech General Practices and high level understanding</p>
<ol>
<li><p>Debit / Credit</p>
</li>
<li><p>Payment Methods / Instruments</p>
</li>
<li><p>Settlements</p>
<ol>
<li><p>End of the day</p>
</li>
<li><p>Start of the day</p>
</li>
<li><p>Session based</p>
</li>
</ol>
</li>
<li><p>Issuance / Acquisition (Issuing / Acquiring)</p>
</li>
<li><p>MDR and MSF</p>
</li>
<li><p>CBS and other Banking Fundamentals</p>
</li>
<li><p>ISO 8583</p>
</li>
<li><p>IPN (Instant Payment Notification)</p>
</li>
<li><p>Payment Idempotency and standard practices</p>
</li>
</ol>
</li>
<li><p>Applications in Fintech</p>
<ol>
<li><p>Paytech</p>
</li>
<li><p>InsurTech</p>
</li>
<li><p>LendTech (P2P Lending, Crowdfunding)</p>
</li>
<li><p>Cryptocurrency and Wallets</p>
</li>
<li><p>Wealth Tech</p>
</li>
<li><p>RegTech</p>
</li>
<li><p>Artificial Intelligence</p>
</li>
<li><p>Open Banking and Other Trends</p>
</li>
</ol>
</li>
<li><p>Building Fintech at Scale</p>
<ol>
<li><p>APIs - HTTP , REST</p>
</li>
<li><p>SaaS and the Cloud</p>
</li>
<li><p>General Software Engineering Guidelines</p>
</li>
<li><p>Design Patterns and Architectures</p>
</li>
<li><p>User interface and user experience principles</p>
</li>
<li><p>Principles of Clean Code Architecture</p>
</li>
<li><p>Microservices</p>
</li>
<li><p>Asynchronous Applications (Real World analogy)</p>
</li>
<li><p>Stateful and Stateless Applications</p>
</li>
<li><p>Connectivity</p>
<ol>
<li><p>VPN</p>
</li>
<li><p>Encryption - Symmetric, Asymmetric and Hashing</p>
</li>
</ol>
</li>
</ol>
</li>
<li><p>Shipping Fintech Application at Scale</p>
<ol>
<li><p>Packaging</p>
<ul>
<li><p>Containerization, Orchestration - concepts, tools and benefits</p>
</li>
<li><p>Introduction to Docker</p>
</li>
<li><p>Microservices architecture and its impact on packaging</p>
</li>
</ul>
</li>
<li><p>Configuration Management and IaC</p>
<ul>
<li><p>Infrastructure as Code (IaC) principles</p>
</li>
<li><p>Tools like Terraform and Ansible for automated configuration management</p>
</li>
<li><p>Versioning the IaC</p>
</li>
<li><p>Consistency, Reproducibility and Configuration Drifts</p>
</li>
</ul>
</li>
<li><p><strong>Deployment Strategies</strong></p>
<ul>
<li><p>Rolling deployments and zero-downtime releases</p>
</li>
<li><p>Blue-green deployments and canary releases</p>
</li>
<li><p>Deployment automation pipelines</p>
</li>
</ul>
</li>
<li><p><strong>Scalability Considerations</strong></p>
<ul>
<li><p>Horizontal vs. vertical scaling</p>
</li>
<li><p>AutoScaling the Cloud and Load Balancing</p>
</li>
<li><p>Handling stateful vs. stateless components in a scalable architecture</p>
</li>
</ul>
</li>
<li><p>SDLC Automation</p>
<ul>
<li><p>Overview of Software Development Life Cycle (SDLC)</p>
</li>
<li><p>Automation tools like Jenkins, GitLab CI/CD</p>
</li>
<li><p>Integration with version control and automated testing</p>
</li>
</ul>
</li>
<li><p>Release Management</p>
<ul>
<li><p>Versioning strategies for releases - (the SemVer)</p>
</li>
<li><p>Release documentation and communication</p>
</li>
<li><p>Rollback strategies in case of deployment failures</p>
</li>
<li><p>Post-deployment monitoring and validation</p>
</li>
</ul>
</li>
<li><p>Database</p>
<ol>
<li><p>RDBMS Design for high scale applications</p>
</li>
<li><p>Schemaless DB Concepts</p>
</li>
<li><p>Streaming Replication in Postgres (Disaster Recovery)</p>
</li>
<li><p>Data Lakes and Abundance of Data in Fintech</p>
</li>
<li><p>TimeScale DB</p>
</li>
</ol>
</li>
<li><p>Reliability Engineering</p>
<ol>
<li><p>Performance Tuning</p>
<ul>
<li><p>Techniques for optimizing code and infrastructure</p>
</li>
<li><p>Load testing and performance monitoring</p>
</li>
<li><p>Scalability considerations in Fintech application</p>
</li>
</ul>
</li>
<li><p>Monitoring and Alerting</p>
<ul>
<li><p>Implementing effective monitoring solutions</p>
</li>
<li><p>Setting up alerts for critical performance metrics</p>
</li>
<li><p>Using APM (Application Performance Monitoring) tool</p>
</li>
</ul>
</li>
</ol>
</li>
<li><p>Cloud and On-Premise Deployments</p>
</li>
<li><p>Security Challenges and Implementation</p>
<ol>
<li><p>Fintech-specific security challenges</p>
</li>
<li><p>Implementing secure coding practices</p>
</li>
<li><p>DevSecOps principles in Fintech development</p>
</li>
<li><p>Risk assessment, fraud detection, and customer insights</p>
</li>
</ol>
</li>
<li><p>Regulatory compliance and data protection in the Fintech industry</p>
</li>
</ol>
</li>
<li><p>Fintech Project Management:</p>
<ol>
<li><p>Agile methodologies in fintech projects</p>
</li>
<li><p>Scrum and Kanban frameworks</p>
</li>
<li><p>Project management tools and best practices</p>
</li>
</ol>
</li>
<li><p>Getting Prepared</p>
<ol>
<li><p>Version Control in Git</p>
</li>
<li><p>Containerization in Docker</p>
</li>
<li><p>Kubernetes</p>
</li>
<li><p>Supervisor and Process Control</p>
</li>
<li><p>RabbitMQ, AMQP, Message Bus and Asynchronous Concepts</p>
</li>
<li><p>Github Actions and Pipeline</p>
</li>
</ol>
</li>
<li><p>The Career Path</p>
<ol>
<li><p>Broader spectrum of Fintech Learning</p>
<ol>
<li><p>Data-driven financial modeling</p>
</li>
<li><p>Machine learning</p>
</li>
<li><p>Financial data analytics (R/Python to perform data analysis)</p>
</li>
<li><p>Cryptocurrency</p>
</li>
<li><p>Cybersecurity</p>
</li>
<li><p>Investment analysis and management</p>
</li>
<li><p>And studying new innovations in AI, blockchain, bitcoin, cloud computing, crowd-funding, P2P lending, and more</p>
</li>
</ol>
</li>
<li><p>Professional Career choices</p>
<ol>
<li><p>Blockchain experts &amp; developers</p>
</li>
<li><p>App developers</p>
</li>
<li><p>AI and machine learning developers</p>
</li>
<li><p>Data scientists</p>
</li>
<li><p>Financial analysts</p>
</li>
<li><p>Product managers</p>
</li>
<li><p>Cybersecurity experts</p>
</li>
<li><p>Risk control managers and compliance managers</p>
</li>
</ol>
</li>
</ol>
</li>
<li><p>Fintech Project (Group Based) in Python / Django / Javascript (React) and Flutter</p>
</li>
</ol>
<h1 id="heading-practical-lab"><strong>Practical Lab</strong></h1>
<p>The course aims to cover a wide range of practical and hands-on sessions, including but not limited to the following scopes.</p>
<ol>
<li><p>Symmetric and Asymmetric Encryption</p>
</li>
<li><p>Setting up the development environment</p>
</li>
<li><p>Containerization and Orchestration</p>
<ol>
<li><p>Set up a Docker environment.</p>
</li>
<li><p>Package a sample application into a Docker container.</p>
</li>
<li><p>Explore basic Docker commands.</p>
</li>
<li><p>Deploy a multi-container application using Kubernetes and Implement scaling and rolling updates</p>
</li>
</ol>
</li>
<li><p>AWS basics</p>
</li>
<li><p>Streaming Replication in PostgreSQL</p>
</li>
<li><p>Continuous Integration and Continuous Deployment</p>
<ol>
<li><p>Implementing a CI/CD pipeline using Github Actions</p>
</li>
<li><p>Automate the testing and deployment process.</p>
</li>
<li><p>Static Code Analysis</p>
</li>
</ol>
</li>
<li><p>Monitoring and Alerting</p>
<ol>
<li><p>Configure monitoring solutions like Prometheus and Grafana.</p>
</li>
<li><p>Set up alerts based on performance metrics</p>
</li>
</ol>
</li>
<li><p>Group Project</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Implementing AWS FireLens with Grafana Loki in AWS ECS]]></title><description><![CDATA[Amazon Elastic Container Service (ECS) is a powerful container orchestration service that simplifies the deployment, management, and scaling of containerized applications. One of its key features is its deep integration with the AWS platform, providi...]]></description><link>https://khalti.engineering/implementing-aws-firelens-with-grafana-loki-in-aws-ecs</link><guid isPermaLink="true">https://khalti.engineering/implementing-aws-firelens-with-grafana-loki-in-aws-ecs</guid><category><![CDATA[AWS]]></category><category><![CDATA[Grafana]]></category><category><![CDATA[Grafana loki]]></category><category><![CDATA[Cloud]]></category><category><![CDATA[fluentbit]]></category><dc:creator><![CDATA[Aman Maharjan]]></dc:creator><pubDate>Thu, 09 Nov 2023 17:13:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1699285346037/bd53ea05-76cc-4fed-a0c4-74a526d8fb03.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Amazon Elastic Container Service (ECS) is a powerful container orchestration service that simplifies the deployment, management, and scaling of containerized applications. One of its key features is its deep integration with the AWS platform, providing a secure and efficient solution for running container workloads. In this blog post, we’ll explore how to enhance your ECS-based applications’ logging capabilities by using AWS FireLens and Grafana Loki for advanced log routing and storage.</p>
<h3 id="heading-why-choose-grafana-loki-over-aws-cloudwatch">Why Choose Grafana Loki Over AWS CloudWatch?</h3>
<p>While AWS CloudWatch is a widely used service for monitoring and logging in the AWS ecosystem, it may have limitations in terms of log collection and analytics, especially for complex, multi-container applications. Here’s why Grafana Loki is a compelling alternative:</p>
<ul>
<li><p><strong>Flexible Log Storage</strong>: Grafana Loki is a powerful log aggregation system that offers flexibility in log storage, allowing you to choose a storage backend that suits your specific needs.</p>
</li>
<li><p><strong>Cost-Effective</strong>: Loki uses a unique indexing mechanism, making it more cost-effective for storing logs compared to traditional solutions like Amazon CloudWatch.</p>
</li>
<li><p><strong>Querying and Visualization</strong>: Loki integrates seamlessly with Grafana, providing advanced query and visualization capabilities, making it easier to analyze and troubleshoot log data.</p>
</li>
<li><p><strong>Highly Scalable</strong>: Loki can be scaled horizontally to handle massive log volumes, ensuring it can grow with your application’s demands.</p>
</li>
</ul>
<p>Fortunately, Grafana provides an official manual for ECS and Loki integration, but it is insufficient when you want to go beyond it. In this article, I will demonstrate my approach to integration.</p>
<h3 id="heading-implementing-firelens-in-aws-ecs">Implementing FireLens in AWS ECS</h3>
<h3 id="heading-what-is-firelens">What is FireLens?</h3>
<p>FireLens is an Amazon ECS container log router that provides a flexible and robust solution for managing logs in your containerized applications. It allows you to route logs to various log storage options, such as Grafana Loki, Elasticsearch, AWS Kinesis Data Firehose/Streams, or other custom solutions.</p>
<p><img src="https://cdn-images-1.medium.com/max/800/1*TF6ZG5n6mzQSXoUU60UovQ.png" alt /></p>
<p>In this section, I’ll provide you with an ECS task definition that leverages AWS FireLens for advanced log routing to Grafana Loki. We’ll highlight the key components and configurations of the task definition.</p>
<pre><code class="lang-plaintext">[
        {
            "name": "log_router",
            "image": "grafana/fluent-bit-plugin-loki:2.9.1",
            "cpu": 0,
            "portMappings": [],
            "essential": true,
            "environment": [],
            "mountPoints": [],
            "volumesFrom": [],
            "user": "0",
            "readonlyRootFilesystem": false,
            "logConfiguration": {
                "logDriver": "awslogs",
                "options": {
                    "awslogs-group": "log_router_log_group",
                    "awslogs-region": "us-west-1",
                    "awslogs-stream-prefix": "firelens"
                },
                "secretOptions": []
            },
            "firelensConfiguration": {
                "type": "fluentbit",
                "options": {
                    "enable-ecs-log-metadata": "true"
                }
            }
        },
        {
            "name": "application",
            "image": "application_image:tag",
            "cpu": 512,
            "memory": 1024,
            "portMappings": [
                {
                    "name": "application-3000-tcp",
                    "containerPort": 3000,
                    "hostPort": 3000,
                    "protocol": "tcp"
                }
            ],
            "essential": true,
            "environment": [
                {
                    "name": "ENVIRONMENT",
                    "value": "dev"
                }
            ],
            "mountPoints": [],
            "volumesFrom": [],
            "readonlyRootFilesystem": false,
            "logConfiguration": {
                "logDriver": "awsfirelens",
                "options": {
                    "LabelKeys": "container_name,ecs_task_definition,source,ecs_cluster",
                    "Labels": "{job=\"firelens-logs\",environment=\"dev\"}",
                    "LineFormat": "key_value",
                    "Name": "grafana-loki",
                    "RemoveKeys": "container_id,ecs_task_arn",
                    "Url": "https://&lt;grafana_loki_url&gt;/loki/api/v1/push"
                },
                "secretOptions": []
            }
        }
]
</code></pre>
<h3 id="heading-key-highlights">Key Highlights</h3>
<p>Here are the important parts of the ECS task definition:</p>
<ul>
<li><p><code>name</code>: The name of the container within the task.</p>
</li>
<li><p><code>image</code>: The container image to use.</p>
</li>
<li><p><code>cpu</code>: The CPU allocation for the container.</p>
</li>
<li><p><code>memory</code>: The memory allocation for the container.</p>
</li>
<li><p><code>portMappings</code>: Defines port mappings for the container.</p>
</li>
<li><p><code>logConfiguration</code>: Configures the log driver and log options for the container.</p>
</li>
<li><p><code>firelensConfiguration</code>: Specifies FireLens as the log router for the container.</p>
</li>
</ul>
<p>Now, let’s proceed to the Terraform code for implementing this task definition in your AWS ECS environment.</p>
<h3 id="heading-terraform-code-for-firelens-implementation">Terraform Code for FireLens Implementation</h3>
<p>Let’s dive into the Terraform code used to implement FireLens in AWS ECS. This code snippet sets up a CloudWatch log group and configures the FireLens log router:</p>
<pre><code class="lang-plaintext">resource "aws_cloudwatch_log_group" "cloudwatch_lg" {
  name = "${var.project_name}-${var.service}-${var.env}"
}

module "fluentbit_definition" {
  source          = "cloudposse/ecs-container-definition/aws"
  version         = "0.58.1"
  container_image = "grafana/fluent-bit-plugin-loki:2.9.1"
  container_name  = "${var.project_name}-log-router-${var.service}-ct"
  firelens_configuration = {
      type = "fluentbit",
      options = {
          enable-ecs-log-metadata = "true"
      }
  }
  log_configuration = {
    logDriver = "awslogs"
    options = {
      awslogs-group         = "${var.project_name}-${var.service}-${var.env}"
      awslogs-region        = var.aws_region
      awslogs-stream-prefix = "firelens"
    }
    secretOptions = []
  }
}

module "app_definition" {
  source          = "cloudposse/ecs-container-definition/aws"
  version         = "0.58.1"
  container_image = "${var.service_ecr_url}:${var.service_image_tag}"
  container_name  = "${var.project_name}-${var.service}-ct"
  container_cpu   = "${var.container_cpu}"
  container_memory = var.container_memory
  port_mappings = [{
    containerPort = var.port
    hostPort      = var.port
    protocol      = "tcp"
  }]

  log_configuration = {
    logDriver = "awsfirelens"
    options = {
      Name  = "grafana-loki"
      Url   = "https://${var.grafana_username}:${var.grafana_password}@${var.grafana_host}/loki/api/v1/push"
      Labels    =  "{job=\"firelens-${var.project_name}-${var.service}\",environment=\"${var.env}\"}"
      RemoveKeys    = "container_id,ecs_task_arn"
      LabelKeys = "container_name,ecs_task_definition,source,ecs_cluster"
      LineFormat    = "key_value"
    }
    secretOptions = []
  }
}

module "taskdefination" {
  source          = "cn-terraform/ecs-fargate-task-definition/aws"
  name_prefix      = "${var.project_name}-${var.service}-td-${var.env}"
  container_cpu    = var.container_cpu
  container_memory = var.container_memory

  containers = [
      module.fluentbit_definition.json_map_object,
      module.app_definition.json_map_object
  ]
}

resource "aws_ecs_service" "service" {
  name                               = "${var.project_name}-${var.service}-${var.env}"
  cluster                            = var.cluster
  deployment_maximum_percent         = 200
  deployment_minimum_healthy_percent = 100
  desired_count                      = 1
  enable_ecs_managed_tags            = false
  health_check_grace_period_seconds  = 0
  launch_type                        = "FARGATE"
  force_new_deployment               = true
  load_balancer {
    target_group_arn = var.target_group_arn
    container_name   = var.container_name
    container_port   = var.container_port
  }
  network_configuration {
    security_groups  = var.security_groups
    subnets          = var.vpc_pub_subnet_ids
    assign_public_ip = true
  }
  platform_version = "1.4.0"
  propagate_tags   = "SERVICE"
  task_definition  = module.taskdefination.aws_ecs_task_definition_td_arn
}
</code></pre>
<p>Let’s break down the key components of this Terraform code:</p>
<ol>
<li><p><code>aws_cloudwatch_log_group</code> Resource: This resource creates a CloudWatch log group with a unique name based on your project, component, and environment. This log group is where your container logs will be stored in CloudWatch.</p>
</li>
<li><p><code>fluentbit_definition</code> Module: This module configures the Fluent Bit container with FireLens for log routing. It uses the <code>grafana/fluent-bit-plugin-loki:2.9.1</code> image for this purpose. Key configurations include:</p>
</li>
</ol>
<ul>
<li><p><code>container_name</code>: Sets the name of the Fluent Bit container.</p>
</li>
<li><p><code>firelens_configuration</code>: Defines FireLens as the log router and enables ECS log metadata.</p>
</li>
<li><p><code>log_configuration</code>: Configures the log driver as <code>awslogs</code>, specifying the CloudWatch log group created earlier, the AWS region, and a stream prefix for log entries.</p>
</li>
</ul>
<p>3. <code>app_definition</code> Module: This module defines the configuration for your application's container. It includes configurations for the application's container image, CPU and memory allocations, port mappings, and log routing. Notable settings include:</p>
<ul>
<li><p><code>container_name</code>: Sets the name of your application's container.</p>
</li>
<li><p><code>log_configuration</code>: Configures the log driver as <code>awsfirelens</code>, routing logs to Grafana Loki. It includes settings for Loki URL, labels, and log format.</p>
</li>
<li><p><code>environment</code>: Allows you to specify environment variables for your container.</p>
</li>
</ul>
<ol>
<li><p><code>taskdefination</code> Module: This module creates an ECS task definition, combining the Fluent Bit and application containers defined in the previous modules. It sets up CPU and memory allocations for the task.</p>
</li>
<li><p><code>aws_ecs_service</code> Resource: This resource creates an ECS service that manages the task deployment. It ensures that the specified number of tasks are running, manages load balancing, and connects to the network. Notable settings include the desired count, load balancing configuration, network setup, and task definition.</p>
</li>
</ol>
<p>With this Terraform code, you have set up a robust logging solution for your AWS ECS containers, routing logs to Grafana Loki for advanced analysis and visualization.</p>
<h3 id="heading-using-grafana-loki-with-firelens">Using Grafana Loki with FireLens</h3>
<p>Now that you have FireLens set up with Grafana Loki, you can start enjoying the benefits of Grafana’s powerful log management and visualization capabilities. Here’s how the integration works:</p>
<ol>
<li><p>Containers in your ECS tasks generate log data.</p>
</li>
<li><p>FireLens routes these logs to Fluent Bit, which is configured to send logs to Grafana Loki.</p>
</li>
<li><p>Grafana Loki stores the log data efficiently, making it available for querying and analysis.</p>
</li>
</ol>
<p>You can use Grafana’s query language and visualization features to gain insights from your log data, helping you troubleshoot issues and monitor the health of your application effectively.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In this blog post, we’ve explored the implementation of AWS FireLens with Grafana Loki in AWS ECS, enhancing your containerized applications’ logging capabilities. By choosing Grafana Loki over AWS CloudWatch, you can enjoy greater flexibility, cost-effectiveness, and advanced log management features.</p>
<p>The provided Terraform code snippet is a valuable resource to get started quickly with FireLens and Grafana Loki. It simplifies the setup, allowing you to focus on gaining insights from your log data and ensuring the reliability of your containerized applications.</p>
<p>With this powerful logging solution in place, you can effectively monitor, troubleshoot, and optimize your containerized applications, ensuring they run smoothly in an AWS ECS environment.</p>
<p><code>Also published on</code> <a target="_blank" href="https://medium.com/@mhrznamn068/implementing-aws-firelens-with-grafana-loki-in-aws-ecs-bdab1c6a6424"><code>Medium</code></a></p>
]]></content:encoded></item><item><title><![CDATA[Monitoring Multiple Kubernetes Clusters with Prometheus Federation]]></title><description><![CDATA[In today’s world of microservices and container orchestration, monitoring is vital to ensuring the health and performance of your applications. When you have multiple Kubernetes clusters in your infrastructure, each hosting different workloads, havin...]]></description><link>https://khalti.engineering/monitoring-multiple-kubernetes-clusters-with-prometheus-federation</link><guid isPermaLink="true">https://khalti.engineering/monitoring-multiple-kubernetes-clusters-with-prometheus-federation</guid><category><![CDATA[Kubernetes]]></category><category><![CDATA[#prometheus]]></category><category><![CDATA[monitoring]]></category><category><![CDATA[#howtos]]></category><category><![CDATA[prometheus-federation]]></category><dc:creator><![CDATA[Anish Sedhai]]></dc:creator><pubDate>Sun, 29 Oct 2023 07:18:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698563825772/2e4e0416-d704-47de-85dd-0471b85c6b0c.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today’s world of microservices and container orchestration, monitoring is vital to ensuring the health and performance of your applications. When you have multiple Kubernetes clusters in your infrastructure, each hosting different workloads, having a centralized monitoring solution becomes crucial. Prometheus, an open-source monitoring and alerting toolkit, is a popular choice due to its flexibility and powerful querying language, PromQL.</p>
<p>This article explores how to effectively monitor and federate data from three Kubernetes clusters. We have one central Prometheus stack that stores data and federates data from two other clusters where Prometheus is deployed using Helm charts with custom configurations.</p>
<p><strong>The Three Kubernetes Clusters</strong></p>
<p>In our setup, we have three Kubernetes clusters. One cluster serves as the central Prometheus stack, while the other two clusters host applications that need monitoring. We’ll refer to these two clusters as “Cluster A” and “Cluster B.”</p>
<p><strong>Configuration of Prometheus Helm Charts</strong></p>
<p>In “Cluster A” and “Cluster B,” we’ve deployed Prometheus using Helm charts with some customizations. One critical customization is disabling persistent volume storage using <code>--set server.persistentVolume.enabled=false</code>. This is done to prevent data storage in the Prometheus instances running in these clusters. Data is centrally stored in the main Prometheus stack.</p>
<p><strong>Central Prometheus Stack Configuration</strong></p>
<p>The central Prometheus stack is where the magic happens. The configuration in its <code>prometheus.yml</code> file is the key to federating data effectively. Let's take a closer look at the relevant configuration:</p>
<pre><code class="lang-plaintext">global:
  # Global configuration options, such as evaluation_interval, scrape_interval, etc.
  scrape_interval: 15s
  evaluation_interval: 15s
scrape_configs:
  - job_name: 'federate'
    scrape_interval: 15s
    honor_labels: true
    metrics_path: '/federate'
    params:
      'match[]':
        - '{job="prometheus"}'
        - '{__name__=~"job:.*"}'
    static_configs:
      - targets:
        - 'source-prometheus-1:9090'
        - 'source-prometheus-2:9090'
remote_write:
  - url: 'http://main-prometheus-federation:9091/write'
</code></pre>
<p>In the <code>prometheus.yml</code> file, we have a <code>scrape_configs</code> section with a job named 'federate.' This job scrapes data from two source Prometheus instances, <code>source-prometheus-1</code> and <code>source-prometheus-2</code>, using the <code>/federate</code> endpoint. The <code>params</code> section specifies matchers to filter the data for federation, including metrics with <code>job="prometheus"</code> and metric names matching the regular expression <code>job:.*</code>. This configuration is designed to collect specific data from the source Prometheus instances for centralized storage.</p>
<p>The <code>params</code> section in the <code>prometheus.yml</code> file is a powerful tool to filter and select the specific metrics you want to federate. In addition to the example provided above, here are a few more examples of regular expressions you can use to filter metrics based on various criteria</p>
<pre><code class="lang-plaintext">params:
  'match[]':
    - '{job="prometheus"}'  # Match metrics with the "job" label equal to "prometheus"
    - '{__name__=~"job:.*"}'  # Match metrics with metric names that start with "job:"
    - '{job=~"web|app"}'  # Match metrics where the "job" label is either "web" or "app"
    - '{environment!="production"}'  # Match metrics where the "environment" label is not "production"
    - '{status_code=~"2..|3.."}'  # Match metrics where the "status_code" label starts with "2" or "3"
</code></pre>
<p>These examples demonstrate how you can use regular expressions and labels to filter metrics based on various conditions. For example:</p>
<ul>
<li><p>The first line matches metrics with the “job” label equal to “prometheus.”</p>
</li>
<li><p>The second line matches metrics with metric names that start with “job:” using the <code>=~</code> operator to specify a regular expression.</p>
</li>
<li><p>The third line matches metrics where the “job” label is either “web” or “app” using the <code>|</code> (pipe) symbol for logical OR.</p>
</li>
<li><p>The fourth line matches metrics where the “environment” label is not “production” using the <code>!=</code> (not equal) operator.</p>
</li>
<li><p>The fifth line matches metrics where the “status_code” label starts with “2” or “3,” which is a common pattern for HTTP status codes.</p>
</li>
</ul>
<p><strong>Federating Data with Prometheus</strong></p>
<p>The term “federation” in Prometheus refers to the process of collecting data from one Prometheus instance into another. In our case, the central Prometheus stack is federating data from “Cluster A” and “Cluster B” by querying their <code>/federate</code> endpoints.</p>
<p><strong>Monitoring in Action</strong></p>
<p>This setup offers numerous benefits, including:</p>
<ul>
<li><p>Centralized Alerting: You can set up alerting rules in the central Prometheus stack to ensure you are promptly notified of issues in any of the monitored clusters.</p>
</li>
<li><p>Dashboarding: You can create dashboards that consolidate metrics from all three clusters, providing a comprehensive view of your infrastructure.</p>
</li>
<li><p>Aggregated Metrics: With federation, you can easily aggregate and query metrics from multiple clusters, simplifying troubleshooting and analysis.</p>
</li>
<li><p>Scalability and Management: This approach is highly scalable and manageable, making it suitable for even larger, more complex Kubernetes environments.</p>
</li>
</ul>
<p><strong>Best Practices and Considerations</strong></p>
<p>When monitoring multiple Kubernetes clusters, it’s important to consider best practices, including:</p>
<ul>
<li>Security: Ensure that your setup includes proper security measures such as network policies, access control, and authentication to protect your monitoring infrastructure.</li>
</ul>
<p><strong>Conclusion</strong></p>
<p>In the world of Kubernetes, monitoring is a critical part of maintaining the health and performance of your applications. With a central Prometheus stack and federation, you can efficiently monitor and aggregate data from multiple clusters, even when deploying Prometheus with custom Helm chart configurations. This setup provides a powerful solution for managing and monitoring complex, multi-cluster Kubernetes environments.</p>
<p>References</p>
<ul>
<li><p><a target="_blank" href="https://prometheus.io/docs/">Prometheus Official Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://prometheus.io/docs/prometheus/latest/federation/">Prometheus Federation</a></p>
</li>
</ul>
<hr />
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Article also published at <a target="_blank" href="https://medium.com/@aniecesedhai/monitoring-multiple-kubernetes-clusters-with-prometheus-federation-264b85abd1cf">medium</a></div>
</div>]]></content:encoded></item><item><title><![CDATA[Deploying a Microservice Application to an AWS ECS Cluster with Terraform, Consul, and Goreman]]></title><description><![CDATA[Introduction:
In this comprehensive guide, we will walk through the process of deploying a microservice application to an Amazon Elastic Container Service (ECS) cluster using a combination of Terraform, Consul, and Goreman. ECS is a scalable and reli...]]></description><link>https://khalti.engineering/deploying-a-microservice-application-to-an-aws-ecs-cluster-with-terraform-consul-and-goreman</link><guid isPermaLink="true">https://khalti.engineering/deploying-a-microservice-application-to-an-aws-ecs-cluster-with-terraform-consul-and-goreman</guid><category><![CDATA[Devops]]></category><category><![CDATA[Terraform]]></category><category><![CDATA[consul]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[Amazon ECS]]></category><dc:creator><![CDATA[Aman Maharjan]]></dc:creator><pubDate>Mon, 03 Jul 2023 14:02:55 GMT</pubDate><content:encoded><![CDATA[<p><strong>Introduction:</strong></p>
<p>In this comprehensive guide, we will walk through the process of deploying a microservice application to an Amazon Elastic Container Service (ECS) cluster using a combination of Terraform, Consul, and Goreman. ECS is a scalable and reliable container orchestration service provided by AWS, Terraform is an Infrastructure as Code (IaC) tool, Consul is a service discovery and configuration management tool, and Goreman helps run multiple services in containers. Together, these tools enable us to provision the necessary AWS resources, manage service discovery, and deploy multiple services within containers in a streamlined manner.</p>
<p>By following the steps outlined in this blog post, you will be able to leverage Terraform to automate the creation of essential AWS resources such as a Virtual Private Cloud (VPC), Elastic Container Registry (ECR), ECS cluster, ECS task definition, and ECS service. Additionally, we will utilize Consul for service discovery and Goreman for running multiple services in containers. Let’s dive in!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688479205585/2259f384-460d-4498-a7b5-811c91454058.png" alt class="image--center mx-auto" /></p>
<p><strong>Microservice architecture:</strong></p>
<p>Microservice architecture is a popular approach for designing and building web and API applications. It involves breaking down a large monolithic application into smaller, loosely coupled services that can be developed, deployed, and scaled independently. Each microservice focuses on a specific business capability and communicates with other microservices through well-defined APIs. This architecture promotes flexibility, scalability, and maintainability, as different services can be developed using different technologies and can be scaled individually based on demand. Additionally, microservices enable teams to work autonomously, allowing for faster development cycles and easier deployment of updates. By adopting a microservice architecture, organizations can build robust and resilient applications that can easily adapt to changing business requirements and handle high traffic loads effectively.</p>
<p><strong>Why Amazon Elastic Container Service (ECS)?</strong></p>
<p>Amazon Elastic Container Service (ECS) offers several advantages when it comes to deploying microservices in a cloud environment. First and foremost, ECS provides a highly scalable and reliable platform for running containers. It allows you to easily deploy and manage containerized microservices, automatically scaling them based on demand. ECS handles all the underlying infrastructure management, such as cluster provisioning, container orchestration, and load balancing, allowing you to focus on developing and deploying your microservices.</p>
<p>Another advantage of ECS is its tight integration with other AWS services. ECS seamlessly integrates with Elastic Load Balancing, Amazon VPC, AWS Identity and Access Management (IAM), and other services, providing a comprehensive solution for building and deploying microservices. This integration allows you to leverage the full power of the AWS ecosystem, enabling features like automatic scaling, centralized logging, security management, and easy integration with other AWS services.</p>
<p>ECS also offers built-in support for service discovery and load balancing. It integrates with Amazon Route 53 and AWS CloudMap to provide dynamic service discovery, allowing your microservices to easily find and communicate with each other. ECS also supports various load balancing options, such as Application Load Balancers and Network Load Balancers, ensuring that traffic is distributed efficiently across your microservices.</p>
<p>Additionally, ECS provides seamless integration with Amazon Elastic Container Registry (ECR), which allows you to store, manage, and deploy container images. ECR provides a secure and scalable repository for your container images, making it easy to version and deploy your microservices.</p>
<p>Furthermore, ECS offers flexibility in terms of deployment options. It supports both Fargate and EC2 launch types, giving you the choice between serverless container deployments or running containers on EC2 instances. This flexibility allows you to select the most suitable deployment option based on your application requirements and cost considerations.</p>
<p>Overall, AWS ECS provides a robust and feature-rich platform for deploying microservices. It simplifies the management of containerized applications, offers tight integration with other AWS services, and provides scalability, reliability, and flexibility, making it an advantageous choice for building and running microservice architectures in the cloud.</p>
<p><strong>Prerequisites:</strong></p>
<p>Before we begin, ensure that you have the following prerequisites in place:</p>
<ul>
<li><p>An AWS account with appropriate permissions to create ECS resources.</p>
</li>
<li><p>Terraform is installed on your local machine.</p>
</li>
<li><p>Basic familiarity with Docker, microservice architecture concepts, and the Consul and Goreman tools.</p>
</li>
</ul>
<p><strong>Step 1: Provisioning Infrastructure with Terraform:</strong></p>
<p>We will start by defining and provisioning our infrastructure using Terraform. This will involve creating a VPC, ECR repository, ECS cluster, ECS task definition, and ECS service. We will also configure the necessary networking components to ensure seamless communication between the containers.</p>
<p><a target="_blank" href="https://github.com/mhrznamn068/ecs-microservice/tree/main/awsinfra/terraform">You can find a sample Terraform infrastructure provisioning code for AWS ECS cluster in this GitHub repository.</a></p>
<p><strong>Step 2: Configuring Service Discovery with Consul:</strong></p>
<p>To enable service discovery within our microservices architecture, we will deploy Consul within our ECS cluster. Consul provides a decentralized system for service discovery, enabling services to register themselves and discover other services dynamically. We will configure Consul agents within the ECS cluster to facilitate service registration and discovery.</p>
<p><a target="_blank" href="https://registry.terraform.io/modules/hashicorp/consul-ecs/aws/latest/examples/dev-server-fargate?product_intent=consul">A module for deploying Consul in ECS can be used for this purpose.</a></p>
<p><em>The Consul with Dev Server on Fargate example installation deploys a sample application in ECS using the Fargate launch type.</em></p>
<p><a target="_blank" href="https://github.com/mhrznamn068/ecs-microservice/blob/main/awsinfra/terraform/modules/ecs/consul.tf">You can find a sample Terraform code to use the above mentioned Consul module.</a></p>
<p><strong>Step 3: Defining and Running Multiple Services with Goreman:</strong></p>
<p>In a microservices architecture, it is common to have multiple services running simultaneously. Goreman allows us to define and manage multiple services within containers using a Procfile-like configuration. We will create a Goreman configuration file and specify the services we want to run, including our application service and Consul agent. Goreman will handle the process management and ensure all services are running correctly.</p>
<p><a target="_blank" href="https://github.com/mhrznamn068/ecs-microservice/tree/main/countries">You can find an example of writing a Dockerfile, structuring project files, and writing a Procfile for Goreman in this GitHub repository.</a></p>
<p><a target="_blank" href="https://github.com/mhrznamn068/ecs-microservice/tree/main/food">Here’s another example for running multiple services using Goreman.</a></p>
<p><strong>Step 4: Building and Pushing Docker Images:</strong></p>
<p>Before deploying our microservices to the ECS cluster, we need to build Docker images for each service and push them to the ECR repository. We will outline the steps to build the Docker images and push them using the AWS Command Line Interface (CLI). Each service’s Dockerfile should be appropriately configured to include all dependencies and configurations.</p>
<p><a target="_blank" href="https://github.com/mhrznamn068/ecs-microservice/blob/main/.github/workflows/main.yml">You can find an example GitHub action workflow for building Docker images in this GitHub repository.</a></p>
<p><strong>Step 5: Deploying Microservices to the ECS Cluster:</strong></p>
<p>With our infrastructure provisioned, Consul running for service discovery, and Docker images built and pushed, we can now deploy our microservices to the ECS cluster. We will utilize the ECS service definition and specify the desired number of tasks for each service. ECS will handle the deployment, scaling, and monitoring of our containers.</p>
<p><a target="_blank" href="https://github.com/mhrznamn068/ecs-microservice/tree/main/awsinfra/terraform/modules/ecs">The ECS task and service definition can be found in this GitHub repository.</a></p>
<p><strong>Conclusion:</strong></p>
<p>In this blog post, we have explored how to deploy a microservice application to an ECS cluster using Terraform for infrastructure provisioning, Consul for service discovery, and Goreman for running multiple services in containers. This powerful combination of tools enables efficient and streamlined management of AWS resources, service discovery, and the deployment of microservices within containers. By following the outlined steps, you can leverage these tools to build and deploy scalable and resilient microservice architectures on AWS. Happy deploying!</p>
<p><a target="_blank" href="https://medium.com/tag/aws?source=post_page-----c3da2c8485e3---------------aws-----------------">  
</a><code>Also published on</code> <a target="_blank" href="https://medium.com/@mhrznamn068/deploying-a-microservice-application-to-an-aws-ecs-cluster-with-terraform-consul-and-goreman-c3da2c8485e3"><code>Medium</code></a></p>
]]></content:encoded></item><item><title><![CDATA[Building immutable infrastructure for your organization using Jenkins, Vault, Packer, Terraform, and Ansible]]></title><description><![CDATA[In today’s fast-paced and dynamic IT landscape, organizations are increasingly adopting immutable infrastructure to improve their deployment processes and enhance system stability. By leveraging tools like Jenkins, Vault, Packer, Terraform, and Ansib...]]></description><link>https://khalti.engineering/building-immutable-infrastructure-for-your-organization-using-jenkins-vault-packer-terraform-and-ansible</link><guid isPermaLink="true">https://khalti.engineering/building-immutable-infrastructure-for-your-organization-using-jenkins-vault-packer-terraform-and-ansible</guid><category><![CDATA[Jenkins]]></category><category><![CDATA[hashicorp-vault]]></category><category><![CDATA[Terraform]]></category><category><![CDATA[ansible]]></category><dc:creator><![CDATA[Anish Sedhai]]></dc:creator><pubDate>Fri, 09 Jun 2023 06:15:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/6AQY7pO1lS0/upload/a76963692fac484fd16960d5da33e4a8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today’s fast-paced and dynamic IT landscape, organizations are increasingly adopting immutable infrastructure to improve their deployment processes and enhance system stability. By leveraging tools like Jenkins, Vault, Packer, Terraform, and Ansible, you can automate the creation and management of infrastructure in a consistent and reproducible manner. In this article, we will explore the benefits of these tools and discuss how they can be integrated to establish a robust and efficient immutable infrastructure pipeline.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698563119135/9cb570e6-13f4-4bd1-8dc4-8dc725deaaed.jpeg" alt class="image--center mx-auto" /></p>
<p>Advantages of Jenkins: Jenkins is a popular open-source automation server that enables the creation of pipelines to automate various stages of software delivery. Its integration with other tools makes it a powerful choice for managing infrastructure as code. Here are some key advantages of Jenkins:</p>
<ol>
<li><p>Continuous Integration and Delivery (CI/CD): Jenkins allows you to define and execute CI/CD pipelines, enabling you to automate the build, test, and deployment processes, reducing manual effort and ensuring consistent releases.</p>
</li>
<li><p>Extensibility: Jenkins offers a vast ecosystem of plugins that can be leveraged to integrate with other tools, enabling seamless orchestration of the entire infrastructure lifecycle.</p>
</li>
<li><p>Scalability: Jenkins supports distributed builds, allowing you to scale your infrastructure as your organization grows. It can handle multiple build agents simultaneously, speeding up the overall process.</p>
</li>
</ol>
<p>Advantages of Packer: Packer is a tool for creating machine images across multiple platforms. It allows you to define infrastructure as code and build images that are consistent, reproducible, and shareable. Here are some advantages of using Packer:</p>
<ol>
<li><p>Immutable Images: Packer generates machine images from a single source configuration, ensuring that the infrastructure remains immutable. This approach promotes consistency and simplifies troubleshooting and rollback processes.</p>
</li>
<li><p>Multi-Platform Support: Packer supports multiple platforms, such as VMware, AWS, Azure, and more, allowing you to create images that can be deployed across different environments, facilitating hybrid and multi-cloud strategies.</p>
</li>
<li><p>Provisioning Flexibility: Packer integrates with configuration management tools like Ansible, enabling you to provision and configure software within the images during the build process, reducing manual intervention and ensuring consistency.</p>
</li>
</ol>
<p>Advantages of Terraform: Terraform is an infrastructure provisioning tool that codifies the desired state of your infrastructure and deploys it across various cloud providers or on-premises environments. Here are some advantages of Terraform:</p>
<ol>
<li><p>Infrastructure as Code: Terraform allows you to define your infrastructure using declarative configuration files. This enables versioning, collaboration, and easy replication of infrastructure across different environments.</p>
</li>
<li><p>Resource Management: Terraform provides a consistent and reliable way to manage resources, allowing you to create, modify, and destroy infrastructure components in a controlled and predictable manner.</p>
</li>
<li><p>Multi-Cloud and Hybrid Cloud Support: Terraform supports a wide range of cloud providers, enabling you to manage infrastructure across multiple clouds or even hybrid environments, giving you the flexibility to choose the best solution for your organization.</p>
</li>
</ol>
<p>Advantages of Ansible: Ansible is a powerful automation tool that simplifies the management and configuration of systems. It follows a “push-based” model and can be seamlessly integrated with other tools in the pipeline. Here are some advantages of Ansible:</p>
<ol>
<li><p>Agentless Architecture: Ansible does not require any agents to be installed on target systems. It uses SSH or WinRM to connect and execute commands remotely, simplifying the setup and reducing the management overhead.</p>
</li>
<li><p>Idempotent Configuration: Ansible applies configurations in an idempotent manner, meaning it ensures that the desired state of the infrastructure is maintained regardless of the number of times the configuration is applied. This promotes consistency and reduces the risk of configuration drift.</p>
</li>
<li><p>Extensibility: Ansible provides a rich set of modules and roles, allowing you to automate various tasks, from simple configuration management to complex orchestration. It integrates well with other tools and can be extended using custom modules as per your organization’s requirements.</p>
</li>
</ol>
<h1 id="heading-lets-outline-the-step-by-step-process"><strong>Let’s outline the step-by-step process</strong></h1>
<p><strong>Define Infrastructure as Code:</strong></p>
<ul>
<li><p>Use a version control system like GitHub to store your infrastructure code, allowing for collaboration and versioning.</p>
</li>
<li><p>Define your infrastructure using Terraform code, specifying resources, networking, and configurations required for your environment.</p>
</li>
<li><p>Store sensitive information like credentials and secrets securely in HashiCorp Vault.</p>
</li>
</ul>
<p><strong>Set Up Jenkins Pipeline:</strong></p>
<ul>
<li><p>Configure Jenkins to create a pipeline that listens for changes in your GitHub repository.</p>
</li>
<li><p>Implement a Jenkins pipeline script that defines the stages and steps for your infrastructure deployment process.</p>
</li>
</ul>
<p><strong>Retrieve Secrets from HashiCorp Vault:</strong></p>
<ul>
<li><p>Integrate Jenkins with HashiCorp Vault using the appropriate plugin.</p>
</li>
<li><p>Pull the necessary variables and secrets from Vault, such as credentials for vSphere.</p>
</li>
</ul>
<p><strong>Initiate Packer:</strong></p>
<ul>
<li><p>Use Packer to define the image build process. Specify the required ISO image, partitions, and software configurations in a Packer template.</p>
</li>
<li><p>In the Jenkins pipeline, trigger Packer to build the virtual machine (VM) image based on the provided build data.</p>
</li>
<li><p>Packer can leverage the secrets retrieved from HashiCorp Vault for vSphere connection.</p>
</li>
</ul>
<p><strong>Convert Image to Template:</strong></p>
<ul>
<li><p>After Packer completes the image creation, convert the image into a template suitable for your virtualization platform (e.g., vCenter).</p>
</li>
<li><p>Store the template in a centralized location accessible to Terraform.</p>
</li>
</ul>
<p><strong>Deploy VMs with Terraform:</strong></p>
<ul>
<li><p>In the Jenkins pipeline, trigger Terraform to provision VMs using the template created in the previous step.</p>
</li>
<li><p>Terraform will use the vSphere provider and the defined Terraform code to create VMs with the desired configuration.</p>
</li>
</ul>
<p><strong>Configure VMs with Ansible:</strong></p>
<ul>
<li><p>Once the VMs are provisioned, trigger Ansible in the Jenkins pipeline to run playbooks for configuring the VMs.</p>
</li>
<li><p>Ansible can leverage the dynamic inventory feature to discover and manage the newly created VMs.</p>
</li>
</ul>
<p>Enhancing the Pipeline with Other Tools: While Jenkins, Packer, Terraform, and Ansible form a powerful foundation for infrastructure, there are several other tools that can enhance your pipeline further:</p>
<ol>
<li><p>Docker: Integrate Docker containers to package your applications and make them more portable, enabling consistent deployment across different environments.</p>
</li>
<li><p>Kubernetes: Use Kubernetes for container orchestration and management, allowing you to scale and manage your applications seamlessly.</p>
</li>
<li><p>Monitoring and Logging Tools: Incorporate tools like Prometheus, Grafana, or ELK stack to gain real-time insights into your infrastructure, enabling proactive monitoring and troubleshooting.</p>
</li>
<li><p>Security Scanning Tools: Integrate security scanning tools like SonarQube or OWASP ZAP into your pipeline to ensure the security of your infrastructure and applications.</p>
</li>
</ol>
<hr />
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This article is also published on <a target="_blank" href="https://medium.com/@aniecesedhai/building-immutable-infrastructure-for-your-organization-using-jenkins-vault-packer-terraform-f440acc83428">Medium</a></div>
</div>]]></content:encoded></item></channel></rss>