<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anderson Leite on Medium]]></title>
        <description><![CDATA[Stories by Anderson Leite on Medium]]></description>
        <link>https://medium.com/@andersonsleite?source=rss-b5a2428d26a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DdDbbB1jnGfcN2Zt</url>
            <title>Stories by Anderson Leite on Medium</title>
            <link>https://medium.com/@andersonsleite?source=rss-b5a2428d26a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 01:10:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andersonsleite/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Keeping costs at bay: Strategies to reduce/control Azure (or any cloud platform) costs]]></title>
            <link>https://andersonsleite.medium.com/keeping-costs-at-bay-strategies-to-reduce-control-azure-or-any-cloud-platform-costs-600d0d2f259f?source=rss-b5a2428d26a------2</link>
            <guid isPermaLink="false">https://medium.com/p/600d0d2f259f</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cloud-cost-optimization]]></category>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud-cost-management]]></category>
            <dc:creator><![CDATA[Anderson Leite]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 10:31:53 GMT</pubDate>
            <atom:updated>2023-11-13T11:59:22.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*pry-M2UOBaI8cmfkFyPWTQ.jpeg" /></figure><p><strong>Introduction</strong></p><p>In the era of cloud computing, organisations worldwide have embraced the flexibility, scalability, and power of cloud platforms like Azure to host their applications and services.</p><p>While the benefits are undeniable, the cost of cloud usage can quickly spiral out of control without the right strategies in place, like the famous meme about AWS costs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*BBrZFh6t913ZC9Vz6Rs1sg.jpeg" /></figure><p>This article aims to be a small guide while you navigate the intricate landscape of cloud cost management, helping you keep your cloud spending under control and maximising the value you receive.</p><p>Some of the actions here are not Azure exclusive (but my focus will be to this one, since it is the cloud provider I&#39;m working with the longest), and can be easily adopted on any other of the major cloud providers, like AWS or GCP.</p><p><strong>What to Expect from This Article</strong></p><p>In this comprehensive guide, we will explore a wide array of strategies and techniques to reduce Azure costs.</p><p>From optimising virtual machine deployments to intelligently managing your cloud expenses, we will cover it all.</p><p>By the time you finish reading, you can expect to achieve the following:</p><p>1. <strong>Cost Savings:</strong> Get insights of practical ways to significantly reduce your Azure spending without compromising performance or functionality. We will explore techniques suitable for both small startups and large enterprises.</p><p>2. <strong>Operational Efficiency:</strong> Discover methods to streamline your Azure operations, making your cloud environment more efficient, manageable, and responsive to your organisation&#39;s needs.</p><p>3. <strong>Effective Resource Utilisation:</strong> Understand the art of right-sizing your workloads, databases, and resources. Unearth insights into avoiding over-provisioning and minimising wastage.</p><p>4. <strong>Comprehensive Cost Management Tools:</strong> Get familiar with Azure’s arsenal of cost management tools and services, such as Azure Cost Management, Azure Advisor, and Azure Policies, to effectively track, optimize, and enforce cost control.</p><p>5. <strong>Strategic Decision-Making:</strong> Gain the knowledge and insights to make informed decisions on resource consolidation, redundancy, and hybrid licensing strategies to balance cost and performance.</p><p>In today’s cloud-centric world, cost management is paramount. Whether you are an IT administrator responsible for cloud resources, a developer working on Azure projects, or a business owner seeking to optimize your cloud investments, this article is tailored to meet your needs. Let’s embark on the journey of cost optimisation in Azure, where financial prudence meets operational excellence.</p><p><strong>1. Using Spot/Preemptible VMs:</strong></p><p>Spot VMs, known by various names across different cloud providers (Azure Spot VMs in Microsoft Azure, AWS Spot Instances in Amazon Web Services, and Preemptible VMs in Google Cloud Platform), offer a unique opportunity to save costs while running workloads in the cloud.</p><p>Note: Two years ago I wrote another article specifically about using Spot VM&#39;s, and you can find it here for extra details about this approach: <a href="https://medium.com/@andersonsleite/reducing-k8s-cluster-costs-with-preemptible-vms-91e379bf2c3a">https://medium.com/@andersonsleite/reducing-k8s-cluster-costs-with-preemptible-vms-91e379bf2c3a</a></p><p><strong>Product page for the offering in each cloud provider:</strong></p><ul><li><strong>Azure Spot VMs (</strong><a href="https://azure.microsoft.com/en-us/products/virtual-machines/spot/">https://azure.microsoft.com/en-us/products/virtual-machines/spot/</a>)</li><li><strong>AWS Spot Instances (</strong><a href="https://aws.amazon.com/ec2/spot/">https://aws.amazon.com/ec2/spot/</a>)</li><li><strong>GCP Preemptible VMs (</strong><a href="https://cloud.google.com/compute/docs/instances/preemptible">https://cloud.google.com/compute/docs/instances/preemptible</a>)</li><li><strong>GCP Spot VM&#39;s (</strong><a href="https://cloud.google.com/spot-vms">https://cloud.google.com/spot-vms</a>)</li></ul><p><strong>Use Cases:</strong> Spot VMs are ideal for tasks such as batch processing, rendering, and workloads that can be interrupted or rescheduled. They are a perfect fit for non-production workloads and applications that can recover gracefully from interruptions (even in production environments in this case!).</p><p><strong>Fault Tolerance:</strong> Since Spot VMs can be preempted when the cloud provider needs the capacity for regular VMs, it is essential to design your applications with fault tolerance in mind. This involves using multiple instances, multiple regions or implementing stateless designs to ensure that your workloads can be rescheduled without data loss or service disruption.</p><p><strong>Cost Savings:</strong> Spot Instances can be significantly cheaper than on-demand instances, making them a popular choice for cost-conscious organisations. They are suitable for a wide range of applications, from batch processing to data analytics.</p><p><strong>Pricing Model:</strong> This aspect is common in any of the major cloud providers: Preemptible VMs are available at a lower price point (discounts can go up to <strong>91%</strong>), making them a cost-effective choice for workloads such as data processing, rendering, and fault-tolerant applications.</p><p><strong>Interruption Management:</strong> Spot Instances are subject to termination if the capacity is needed by regular on-demand instances:</p><ul><li>AWS provides a <strong>two-minute</strong> warning before interrupting Spot Instances.</li><li>Azure provides a <strong>one-minute</strong> warning</li><li>GCP VM&#39;s can be run <strong>up to</strong> 24 hours and Google provides a <strong>30-second</strong> notification before the eviction of the node happen for preemptible VM&#39;s and <strong>1-hour</strong> notice notification before the eviction of the node happen, in case of VM&#39;s with GPU&#39;s</li></ul><p>Like said before, each of these cloud providers offers their own version of spot instances, providing you with the flexibility to choose the one that best aligns with your specific cloud needs. Whether you are in Azure, AWS, or GCP, utilising spot instances can lead to substantial cost savings without compromising performance, making them a valuable tool in your cloud cost optimisation toolkit.</p><p>While using GCP, you can even consider the usage of noderecycler — <a href="https://github.com/playerme/noderecycler">https://github.com/playerme/noderecycler</a> (written by my friend <a href="https://github.com/psychopenguin">Fabio</a> and ported to go by my another friend <a href="https://github.com/maktouch">Makara</a>) to ensure the nodes on GCP are evicted on a controlled way (with a drain of the pods) before the eviction time (24h) are reached out and GCP evicts it from the cluster.</p><p>Expanding a bit about &quot;fault-tolerant applications&quot;: In this case, I&#39;m assuming you are running a kubernetes cluster, and in this cluster you have at least one node pool running backed by spot VM&#39;s. On this node pool we will schedule workloads which can survive the eviction of one (or more) pods, using one or more the following strategies:</p><ul><li>Set the number of replicas for this deployment to at least 2</li><li>Set affinity and toleration rules (use <strong>nodeAffinity</strong>), to ensure the workload will run on the spot node pool</li><li>Define anti-affinity rules (use <strong>podAntiAffinity</strong> in this case) to make sure two replicas from the same deployment will not be scheduled at the same node, with that in place, when the node got evicted, the application will continue to serve requests with the remaining pods</li></ul><p>You can find some examples on the official kubernetes documentation:</p><ul><li>Node affinity: <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity">https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity</a></li><li>Pod antiAffinity: <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#more-practical-use-cases">https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#more-practical-use-cases</a></li></ul><p><strong>2. Right Sizing Workloads:</strong></p><p>Right-sizing your workloads are crucial to avoid over-provisioning and unnecessary costs. Start by analysing historical usage data to understand your application’s resource requirements. Some examples:</p><p>- Use your monitoring solution to check the CPU/Memory utilisation and compare it against the requests/limits set to the workloads. This step will save a considerable amount of money for sure since in most cases the applications tend to consume a lot of resources during the startup and keep an average usage afterwards, so the spike can be easily provided with an over-provision approach based on the limits. My advice here it is to keep the over-provision around 50% of the node total resources.</p><p>- Use Azure Monitor to gather performance data and analyse resource utilisation. This information can help you identify underutilised or over-provisioned VMs.</p><p>- Azure Cost Management and Billing can provide insights into your usage and spending patterns, helping you make informed decisions about right-sizing your resources.</p><p>- Consider using tools like Azure VM Analyser, which can recommend suitable VM sizes based on historical usage patterns.</p><p>My good friend <a href="https://github.com/frank-dornberger">Frank Dornberger</a> presented last year on <a href="https://newrelic.com/futurestack">NewRelic&#39;s FutureStack</a> a workshop about how monitor / right-size your applications using NewRelic monitoring capabilities. The code used at the demo (and the NR dashboard) can be found here <a href="https://github.com/frank-dornberger/futurestack-2022-workshop">https://github.com/frank-dornberger/futurestack-2022-workshop</a></p><p>A note about <strong>NewRelic</strong>: The company offers a free tier, up to 100GB of ingested data per month, which can be useful while analysing cluster workload usage. For additional information about NewRelic free tier, refer to this page <a href="https://newrelic.com/pricing/free-tier">https://newrelic.com/pricing/free-tier</a>.</p><p><strong>3. Auto Shutdown Policies:</strong></p><p>Implementing auto shutdown policies for non-production VMs is a straightforward way to save costs. As before, we can find this function on all three big providers:</p><ul><li>Azure <a href="https://learn.microsoft.com/en-us/azure/devtest-labs/devtest-lab-auto-shutdown">https://learn.microsoft.com/en-us/azure/devtest-labs/devtest-lab-auto-shutdown</a></li><li>AWS <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-termination-policies.html">https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-termination-policies.html</a></li><li>GCP <a href="https://cloud.google.com/compute/docs/instances/schedule-instance-start-stop">https://cloud.google.com/compute/docs/instances/schedule-instance-start-stop</a></li></ul><p>Your mileage may vary from provider to provider, but at the end, all three will provide one (or more) ways to automatically shutdown some VM&#39;s and with that, save some extra bucks.</p><p>- Azure Virtual Machine features an Auto-Shutdown setting, allowing you to specify the shutdown time and time zone. This is particularly useful for development and test environments that are typically used during business hours. You can also use Azure Logic Apps or Azure Functions to create custom auto-shutdown policies, providing more flexibility in scheduling.</p><p>- Ensure that your organisation communicates and educates users about the auto-shutdown policies to avoid interruptions or unexpected downtime.</p><p><strong>4. Database Workload Consolidation:</strong></p><p>Consolidating database workloads can lead to substantial cost savings and improved resource utilisation. Consider the following strategies:</p><p>- Consolidate several small managed instances in a single beefier instance: With that, you can move from, let&#39;s say: 8 Managed PostgreSQL instances running at basic SKU with 2 vCores each, and move it to a single instance, Memory Optimised with 4vCores, which can seamless be called up to 32vCores, if needed, and also provide us extra capabilities like encryption and zone-redundancy. An extra perk of the memory optimised SKU besides more memory, it this one also accepts a higher number of simultaneous connections.</p><p>- Use Azure SQL Database elastic pools to consolidate multiple databases with varying usage patterns into a single pool. This optimizes resource allocation and reduces costs.</p><p>- Right-size your databases by selecting an appropriate performance tier and adjusting the number of elastic database transaction units (eDTUs) — Specific to Azure SQL Database service — based on workload requirements.</p><p>- Regularly review database usage and adjust to the pool and database configurations as needed.</p><p><strong>A bit more about eDTUs on Azure SQL:</strong></p><p>Elastic Database Transaction Units (eDTUs) are a vital part of Microsoft Azure’s database performance scaling. They are a measure of the overall performance capacity that a database can provide within the Azure SQL Database service. eDTUs encompass both the database’s processing power and storage capacity, offering a unified metric for evaluating a database’s performance characteristics. Here is what you need to know about eDTUs:</p><p><strong>- Combining Processing and Storage:</strong> eDTUs account for both CPU processing power and storage capacity. This is crucial because a optimised database must not only have enough CPU power to handle transactions but also sufficient storage to hold data and indexes.</p><p><strong>- Performance Tiers: </strong>In Azure SQL Database, databases are categorised into performance tiers, each of which is assigned a specific number of eDTUs. These tiers range from Basic to Premium, and the higher the tier, the more eDTUs are allocated to the database.</p><p><strong>- Customisable Scaling:</strong> Azure SQL Database provides the flexibility to adjust the number of eDTUs assigned to a database based on workload requirements. You can scale up or down within the same performance tier to accommodate changing demands, ensuring that you are only paying for the performance you need.</p><p><strong>- Balancing Cost and Performance:</strong> Choosing the right number of eDTUs is a balance between cost and performance. Higher eDTU levels provide more processing power and storage but come at a higher cost. By accurately matching your database’s eDTUs to your workload requirements, you can save costs while delivering optimal performance.</p><p><strong>- Monitoring and Adjusting: </strong>Regularly monitor your database’s performance metrics, such as CPU utilisation, to ensure that the chosen eDTU level aligns with your workload demands. If you notice that performance is consistently below expectations, you can consider scaling up the number of eDTUs to improve it. Conversely, you can scale down to save costs during periods of lower activity.</p><p>eDTUs are a versatile metric in Azure SQL Database that allows you to quantify the performance and storage needs of your databases. They provide the agility to fine-tune database performance while managing costs effectively, making them a valuable tool for right-sizing your databases in Azure. By understanding eDTUs and their role in database performance, you can ensure that your databases deliver the performance you need without over-provisioning or overspending.</p><p><strong>5. Balancing Resource Consolidation and Redundancy:</strong></p><p>Finding the right balance between resource consolidation and redundancy is critical for cost optimisation. Factors to consider include:</p><p>- Evaluate the importance of data redundancy for your applications. For mission-critical workloads, redundancy may be necessary, but for non-critical workloads, it might not be cost-effective.</p><p>- Use Azure Traffic Manager to distribute traffic across different Azure regions efficiently. This can help in achieving redundancy while optimizing data transfer costs.</p><p>- Implement geo-replication and failover strategies for critical workloads while considering the cost implications.</p><p><strong>6. Azure Cost Management for Partners, CSPs, and Enterprise Agreements:</strong></p><p>Azure offers distinct options for managing costs across different scenarios. Each of these options provides features tailored to specific needs:</p><p>- <strong>Azure Cost Management for Partners:</strong> Designed for partners working with multiple customers, this tool allows you to gain insights into the cost and usage of each customer’s Azure environment. It simplifies the process of managing costs for various clients.</p><p>- <strong>Azure Cost Management for CSPs (Cloud Solution Providers):</strong> This option is specifically built for CSPs to manage costs for their customers efficiently. It offers detailed insights into consumption and helps in billing and invoicing processes.</p><p>- <strong>Azure Cost Management for Enterprise Agreements:</strong> Enterprise Agreements often encompass multiple departments and teams. This tool enables organisations to track and optimize costs across various departments or business units within a single agreement.</p><p>- <strong>Azure Cost Management for Microsoft Customer Agreement:</strong> Ideal for organisations operating under the Microsoft Customer Agreement, this tool helps manage costs across multiple departments while ensuring compliance with the agreement’s terms.</p><p><strong>7. Leveraging Azure Advisor:</strong></p><p>Azure Advisor is a powerful tool that provides recommendations for optimising your Azure resources. It covers several aspects, including:</p><p>- <strong>Cost Recommendations:</strong> These recommendations focus on cost-saving opportunities. Azure Advisor may suggest options like resizing underutilised VMs, purchasing reserved instances, or deleting unused resources.</p><p>- <strong>Performance Recommendations:</strong> Advisor offers advice on improving the performance of your resources. This includes suggestions for optimising virtual machine configurations, enhancing security, and more.</p><p>- <strong>Security Recommendations:</strong> Advisor can help identify and address potential security vulnerabilities within your Azure environment, ensuring your resources are secure and compliant.</p><p>- <strong>Operational Excellence Recommendations:</strong> This category focuses on best practices and improvements to enhance your operational efficiency, such as automating routine tasks or implementing monitoring solutions.</p><p><strong>8. Utilising Azure Reservations:</strong></p><p>Azure Reservations offer substantial savings for organisations that have predictable workloads. Here is how to effectively use them:</p><p>Certainly, let’s expand on how Reserved Instances (RIs) work in Azure and discuss the capability to change from one VM size to another within the same family type:</p><p><strong>Understanding Azure Reserved Instances (RIs):</strong></p><p>Azure Reserved Instances (RIs) are a powerful tool for cost optimisation within Microsoft Azure. They allow you to commit to a one- or three-year term for virtual machines (VMs) and other Azure resources, resulting in substantial cost savings compared to pay-as-you-go pricing. Here is how RIs work:</p><p>- <strong>Cost Savings: </strong>By reserving a VM for a specific term, you are prepaying for the compute capacity, and in return, you receive a significantly discounted rate. RIs offer a lower cost per hour compared to on-demand pricing.</p><p>- <strong>Flexibility:</strong> RIs are available for various Azure resources, including Virtual Machines, SQL Databases, and more. You can select the term (one or three years) and payment option (upfront, monthly, or yearly) that best suits your organisations financial model.</p><p>- <strong>Reservation Scope: </strong>When you purchase an RI, it is associated with a specific Azure region and VM family type. This means you commit to a VM size within that family type for the duration of the reservation.</p><p><strong>Changing VM Size within the Same Family Type:</strong></p><p>Azure provides the flexibility to change from one VM size to another within the same family type, allowing you to adapt to changing workload requirements or take advantage of different VM configurations while still benefiting from your existing RI. Here is how this capability works:</p><p>- <strong>Consistency within Family Type: </strong>Azure VMs are organised into families based on characteristics like CPU, memory, and performance. When you purchase an RI for a specific VM family, you can change your VM size within that family type without losing the benefits of the reservation.</p><p><strong><em>Example Scenario:</em></strong><em> </em>Suppose you initially reserved an RI for a VM in the Dv3 family (let&#39;s say: 8x <strong>Standard_D8s_v3</strong> VM&#39;s), which is known for its balanced CPU and memory performance. As your workload evolves, you may find the need for more compute power without wanting to lose the benefits of your reservation. In this case, you can switch to a larger VM within the same Dv3 family (let&#39;s say: 4x <strong>Standard_D16s_v3</strong> VM’s), accommodating your growing needs while continuing to enjoy the cost savings of your existing RI.</p><p>- <strong>Flexibility and Cost Savings:</strong> This flexibility allows you to optimize your resource usage. It’s a valuable feature for organisations that need to scale their resources up or down based on changing workloads while maintaining cost-effectiveness.</p><p>In summary, Azure Reserved Instances provide a powerful mechanism for reducing costs while ensuring resource availability. The capability to change VM sizes within the same family type enhances this cost-saving strategy by allowing you to adapt to your evolving needs without losing the benefits of your existing RIs. This feature empowers you to maintain the perfect balance between resource flexibility and cost control within Microsoft Azure.</p><p>You can also take a &quot;mix and match&quot; approach (Thanks <a href="https://github.com/gmotasilva">Gustavo</a>!) using an Azure Savings plan together with reserved instances and maximise your savings at the end of the month.</p><p>Other insight Gustavo gave me was make a combo using Azure Savings plan tied together with Azure fixed costs model (which make you pay a fixed value per hour, but use it at any service). Here (<a href="https://learn.microsoft.com/en-us/azure/well-architected/cost/design-price">https://learn.microsoft.com/en-us/azure/well-architected/cost/design-price</a>) you can find a bit more of information about fixed price.</p><p><strong>9. Azure Dev/Test Pricing:</strong></p><p>Azure Dev/Test Pricing is a cost-effective option for development and testing environments. It offers reduced rates for specific services to save on resource costs. Key points to consider include:</p><p>- Azure Dev/Test Pricing applies to services like Virtual Machines, SQL Database, and App Service.</p><p>- Dev/Test VMs are typically available at a fraction of the regular price, making them ideal for non-production environments.</p><p>- Make use of Visual Studio Subscriptions, which come with Azure Dev/Test benefits, to further maximize cost savings for development and testing scenarios.</p><p><strong>10. Azure Budgets and Notifications:</strong></p><p>Azure Budgets and notifications help you stay in control of your spending. Here is how to effectively use them:</p><p>- Create Azure Budgets to set cost thresholds for your resources or services. You can set up budgets by subscription, resource group, or resource. Establish clear limits to avoid unexpected costs.</p><p>- Configure notifications to alert you when you are approaching or exceeding your budget thresholds. Notifications can be sent via email, SMS, or integrated with third-party applications through webhooks.</p><p>- Regularly review your budgets and adjust them as your usage and cost expectations change.</p><p><strong>11. Azure Policies for Cost Management:</strong></p><p>Azure Policies allow you to enforce rules and standards to maintain cost control. Here is how to use them effectively:</p><p>- Define policies that align with your organisations cost management and compliance requirements. For example, you can create policies that prevent the deployment of costly resources or enforce naming conventions for better cost tracking.</p><p>- Assign policies to your Azure resources, subscriptions, or management groups to ensure compliance. Azure Policy can help you evaluate and enforce these policies automatically.</p><p>- Continuously monitor policy compliance and adjust as needed to adapt to changing organisational requirements.</p><p><strong>12. Azure Hybrid Benefit for Windows and SQL Server:</strong></p><p>Azure Hybrid Benefit is a cost-saving option for organisations with existing licenses for Windows Server and SQL Server. Here is how it works:</p><p>- You can apply Azure Hybrid Benefit to reduce the cost of running Windows Server and SQL Server workloads in Azure. This allows you to leverage your existing licenses in the cloud.</p><p>- Ensure that your licenses are eligible for Azure Hybrid Benefit, and then configure your Azure VMs to take advantage of the benefit.</p><p>- Regularly validate the compliance of your licenses and optimize your VMs to make the most of the cost savings offered by the Azure Hybrid Benefit.</p><p><strong>13. Third-party options (free, free trial or paid):</strong></p><p>I&#39;m not the first (and surely will not be the last) thinking about strategies to <strong>spend better</strong> on cloud solutions, some solutions from third parties are already in the market and can be useful to analyse and detect cost improvements. Here a small list (no specific ordering) with some options:</p><ul><li><a href="https://www.flexera.com/flexera-one/cloud-cost-optimization">https://www.flexera.com/flexera-one/cloud-cost-optimization</a></li><li><a href="https://www.ibm.com/products/turbonomic">https://www.ibm.com/products/turbonomic</a></li><li><a href="https://spot.io/solutions/finops/">https://spot.io/solutions/finops/</a></li><li><a href="https://www.apptio.com/solutions/cfm/ccmo/">https://www.apptio.com/solutions/cfm/ccmo/</a></li><li><a href="https://www.datadoghq.com/dg/ccm/cloud-cost-management">https://www.datadoghq.com/dg/ccm/cloud-cost-management</a></li><li><a href="https://www.kubecost.com/">https://www.kubecost.com/</a></li><li><a href="https://www.opencost.io/">https://www.opencost.io/</a></li><li><a href="https://piercloud.com.br/en/">https://piercloud.com.br/en/</a></li></ul><p>AWS also provides a <a href="https://aws.amazon.com/aws-cost-management/aws-cost-anomaly-detection/">Cost Anomaly Detection</a>, which can help folks running workloads in this cloud provider to early detect deviations (and prevent a big bill at the end of the month)</p><p><strong>Recap:</strong></p><p>So, in short, those are some actions you can take to reduce your Azure costs</p><p>At <strong>infrastructure level</strong>, you can:</p><p>- Use Spot VMs to save money on compute resources (specially for non-production VM’s and on kubernetes clusters where workloads can be rescheduled and keep serving connections since it has more than 1 replica and/or are stateless)</p><p>- Right size the workloads requests and limits accordingly to the historic usage, to reduce the over-provisioning</p><p>- Implement an auto shutdown policy for VM’s on non-production environments</p><p>- Consolidate database workloads to reduce the number of managed instances, properly sizing also helps</p><p>- Consider the balance between consolidate resources in a single region and enable redundancy to reduce the costs of data transfer between regions</p><p>At <strong>company / partnership level</strong>, you can explore one of the following options:</p><p>- Use Azure Cost Management for partners to manage costs for multiple customers</p><p>- Use Azure Cost Management for CSPs to manage costs for multiple customers</p><p>- Use Azure Cost Management for Enterprise Agreements to manage costs for multiple departments</p><p>- Use Azure Cost Management for Microsoft Customer Agreement to manage costs for multiple departments</p><p><strong>Planning or insight tools/actions </strong>you can explore at side:</p><p>- Use Azure Advisor to get recommendations on how to reduce costs</p><p>- Use Azure Cost Management to get insights on how to reduce costs</p><p>- Use Azure Reservations to save money on compute resources</p><p>- Use Azure Dev/Test Pricing to save money on development and testing</p><p>Day to day / monitoring actions you can explore:</p><p>- Use Azure Budgets to set a budget and get notified when you are about to exceed it</p><p>- Use Azure Policies to enforce cost management rules</p><p>- AWS offers a extensive documentation, called &quot;AWS Well Architected&quot; (<a href="https://aws.amazon.com/architecture/well-architected">https://aws.amazon.com/architecture/well-architected</a>), and one of the sections are related to costs (<a href="https://docs.aws.amazon.com/wellarchitected/latest/cost-optimization-pillar/practice-cloud-financial-management.html">https://docs.aws.amazon.com/wellarchitected/latest/cost-optimization-pillar/practice-cloud-financial-management.html</a>)</p><p>If using Windows and/or SQL Server, you can also explore the use of Azure Hybrid Benefit to save money on Windows Server and SQL Server licenses</p><p><strong>Conclusion:</strong></p><p>In the ever-evolving realm of cloud computing, the ability to control costs while harnessing the immense power of cloud platforms is a skill that cannot be underestimated. As we conclude this exploration of strategies to reduce costs, it is important to emphasise that cost management in the cloud is an ongoing journey. The dynamic nature of cloud providers offer means that staying within budget and optimising your resources is a continuous effort.</p><p>By implementing the strategies and best practices outlined in this article, you are taking a significant step toward achieving financial prudence, operational efficiency, and the ability to extract maximum value from your Azure investments. The lessons learned here are not just for the moment but for the long run, helping your organisation thrive in the cloud era.</p><p>As recent technologies and features emerge, staying updated on cost management trends and tools will be crucial. Keep a watchful eye on Azure’s (and other cloud providers) ever-evolving ecosystem, adapt your strategies as needed, and continue to balance cost and performance for your cloud workloads.</p><p>In the end, effective cost management isn’t just about spending less; it is also spending smarter. The cloud’s boundless potential awaits those who can navigate its cost-effective pathways while reaching new heights of innovation and productivity.</p><p>Thank you for joining on this journey. May your cloud deployments be efficient, your budgets well-managed, and your cloud endeavours endlessly rewarding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=600d0d2f259f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Hashicorp Vault w/ auto unseal (using Azure), GitLab and Kubernetes integrated]]></title>
            <link>https://andersonsleite.medium.com/deploy-hashicorp-vault-w-auto-unseal-using-azure-gitlab-and-kubernetes-integrated-241e888ac94e?source=rss-b5a2428d26a------2</link>
            <guid isPermaLink="false">https://medium.com/p/241e888ac94e</guid>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[azure-key-vault]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Anderson Leite]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 08:33:33 GMT</pubDate>
            <atom:updated>2021-02-23T08:33:33.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*Ii27u7X690t44Ux9kfDWhg.png" /></figure><h3>Introduction</h3><p>In the customer I&#39;m currently working, the secret values used to deploy the applications are currently stored as GitLab variables (protected and masked, of course, but still its a variable which can be easily visible to somebody with access to repo).</p><p>During one of our <em>innovation weeks</em> (which happens at the end of each cycle = every 3 months), I&#39;ve done a proof of concept to try to integrate <a href="https://www.vaultproject.io/">Hashicorp&#39;s Vault</a> in our environment, and use it to provide secret values to GitLab variables (during pipeline runtime), Kubernetes and our SpringBoot applications.</p><p>What we will &quot;glue up&quot; together here today:</p><ul><li><a href="https://www.vaultproject.io/">Vault by Hashicorp</a></li><li><a href="https://kubernetes.io/">Kubernetes</a></li><li><a href="https://docs.microsoft.com/en-us/azure/key-vault/general/basic-concepts">Azure Key Vault</a> (to store the secret used to autounseal the vault)</li><li><a href="https://about.gitlab.com/">GitLab</a></li><li><a href="https://spring.io/">SpringBoot</a> (just some references)</li></ul><p>Shall we start ?</p><h3>What is a vault ?</h3><p>Vault is a tool for securely accessing <strong><em>secrets</em></strong>. A secret is anything that you want to tightly control access to, such as API keys, passwords, or certificates. Vault provides a unified interface to any secret, while providing tight access control and recording a detailed audit log.</p><p>A modern system requires access to a multitude of secrets: database credentials, API keys for external services, credentials for service-oriented architecture communication, etc. Understanding who is accessing what secrets is already very difficult and platform-specific. Adding on key rolling, secure storage, and detailed audit logs is almost impossible without a custom solution.</p><p>The key features of Vault are:</p><ul><li><strong>Secure Secret Storage</strong>: Arbitrary key/value secrets can be stored in Vault. Vault encrypts these secrets prior to writing them to persistent storage, so gaining access to the raw storage isn’t enough to access your secrets. Vault can write to disk, <a href="https://www.consul.io/">Consul</a>, <em>raft </em>storage and more.</li><li><strong>Dynamic Secrets</strong>: Vault can generate secrets on-demand for some systems, such as AWS or SQL databases. For example, when an application needs to access an S3 bucket, it asks Vault for credentials, and Vault will generate an AWS keypair with valid permissions on demand. After creating these dynamic secrets, Vault will also automatically revoke them after the lease is up.</li><li><strong>Data Encryption</strong>: Vault can encrypt and decrypt data without storing it. This allows security teams to define encryption parameters and developers to store encrypted data in a location such as SQL without having to design their own encryption methods.</li><li><strong>Leasing and Renewal</strong>: All secrets in Vault have a <em>lease</em> associated with them. At the end of the lease, Vault will automatically revoke that secret. Clients are able to renew leases via built-in renew APIs.</li><li><strong>Revocation</strong>: Vault has built-in support for secret revocation. Vault can revoke not only single secrets, but a tree of secrets, for example all secrets read by a specific user, or all secrets of a particular type. Revocation assists in key rolling as well as locking down systems in the case of an intrusion.</li></ul><p>About GitLab integration: Since 12.9 GitLab already have vault capabilities integrated, <a href="https://about.gitlab.com/releases/2020/03/22/gitlab-12-9-released/">as stated here</a>. In my customer case the best approach (in my opinion) was use something like “<a href="https://gitlab.com/groups/gitlab-org/-/epics/2868">Bring Your Own HashiCorp Vault Integration</a>”</p><h3>Setting vault automatic unsealing using MS Azure</h3><p>The big advantage of use Azure (or any other cloud provider) to auto-unseal your vault is don&#39;t have the need of securely distribute the parts of the main secret (you should of course store it anyway, otherwise you will not able to unseal your vault in case of problems with the cloud provider for example), using the auto unseal, if the deployment of vault got restarted (by any circumstance), the secret will be fetched from the cloud provider, auto unseal the vault and the services which uses it keep up and running.</p><p>The steps needed to setup the automatic unsealing with MS Azure are:</p><ul><li>Create an instance of Azure Key Vault on a existing service principal (App registration)</li><li>Create a client in the given service principal</li><li>Add Key Vault Contributor role to the given service principal</li><li>Create a key on the Key Vault</li></ul><h3>Create an instance of Azure Key Vault with a existing service principal</h3><p>To do that, go to <a href="https://portal.azure.com/#blade/HubsExtension/BrowseResource/resourceType/Microsoft.KeyVault%2Fvaults">Key Vaults in MS Azure Portal</a> and click on Add button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xr2FwAHT3TAwgxbvfTqvcQ.png" /><figcaption>Key vaults page in MS Azure Portal</figcaption></figure><p>(in our case, the key vault which will be used its the “vault-key-data” listed in the image above)</p><p><strong>Example of Key vault creation:</strong></p><blockquote><strong><em>Note: </em></strong>For now, the default options are OK for us, just click in “Review + create” to proceed.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*dnpdoIrXZCqAADzDE3LM3A.png" /></figure><h3>Create a client in the given service principal</h3><p>With the Key Vault created, go to <a href="https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade">App registrations page</a>, in order to create a new client in our service principal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*5Qq4FdtEpCNCIvttzjjDyg.png" /></figure><p>Click in the service principal where you want to create the new client, in the new page, at the left menu, click in “<strong>Certificates &amp; secrets</strong>” option, and in right pane, click in “<strong>+ New client secre</strong>t” option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pg0pLcLTqXl49Tka3YpBxQ.png" /></figure><p>In the modal shown, fill the required information and click in “<strong>Add</strong>” to finish:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*ohStkjYj4oEkqtIHFf7D_A.png" /></figure><p>Back to Client secrets, write down the value of the client secret, since if you leave this page that will not be completely shown anymore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*S7JcIhSlyW-qy3RUa--3Ng.png" /></figure><p>(The <strong><em>test-client-secret</em></strong> its shown here because just before this image been added here, the secret has been deleted)</p><p>Now, go back to App registration screen and also write down:</p><ul><li><strong><em>Application (client) ID</em></strong></li><li><strong><em>Directory (tenant) ID</em></strong></li><li><strong><em>Object ID</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*xbaOj2gWfO5asDdD2TaiIw.png" /></figure><h3>Add Key Vault Contributor role to the given service principal</h3><p>Now, go back to <a href="https://portal.azure.com/#blade/HubsExtension/BrowseResource/resourceType/Microsoft.KeyVault%2Fvaults">Key Vaults page</a>, where we will add the key vault contributor role to our service principal.</p><p>To do that, enter in our vault, and in the left pane, click in “<strong>Access Control (IAM)</strong>” option, and in right pane, click in “<strong>+ Add</strong>” button and select the option “Add role assignment”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*qGuvSeowJBdGKAceR_sa0w.png" /></figure><p>That will open a side panel where we must select the role to add, and the service principal which will be added to this role, select “<strong>Key Vault Contributor</strong>” in the <em>Role</em> field<strong>, </strong>select the service principal to be added in “<strong>Select</strong>”<strong> </strong>field (when you start to type the name, it applies a filter and you can select it in box below), and click in “<strong>Save</strong>” to proceed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*F_yFk9oaDfaCChpArF4TWg.png" /></figure><p>Now, yet in Key Vaults detail pane, go to “Access Policies” and click in “<strong>+ Add Access Policy</strong>”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*JMKBkx2upXzYIM3EPW3-QQ.png" /></figure><p>In Add access policy pane, we will create a policy with the following options selected at “Key permissions” field:</p><ul><li><strong>Key Management Operations</strong></li><li><em>Get</em></li><li><strong>Cryptographic Operations</strong></li><li><em>Unwrap Key</em></li><li><em>Wrap Key</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*Jyig4UU7eKC92W0fRl3pGg.png" /></figure><p>After that, click at “<strong>None selected</strong>” in “<strong>Select principal</strong>” field, select our target service principal and click in “<strong>Add</strong>” to finish the access policy creation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NRbUis7ZBKNS2q4tzcASew.png" /></figure><p>The result before clicking “Add” button should looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_VLk7Db-bnxPXmCLt0Lfg.png" /></figure><h3>Create a key on the Key Vault</h3><p>The last step in azure portal is create a key, which will be used to unseal the vault in kubernetes.</p><p>To do that, in <a href="https://portal.azure.com/#blade/HubsExtension/BrowseResource/resourceType/Microsoft.KeyVault%2Fvaults">Key Vaults page in MS Azure Portal</a>, enter in our vault and select the “<strong>Keys</strong>” option at left menu and in right pane, click at “<strong>+ Generate/Impor</strong>t” button to create a new key:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*A0FRSPRvrAHT-pm-N-sEJg.png" /></figure><p>Enter a name for the key, adjust the “<strong>RSA Key Size</strong>” parameter as needed and click at “<strong>Create”</strong> button at the bottom of the page to finish the key creation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*bDEnhGybCpVs2AeDtfLhBA.png" /></figure><p>And we’re done with Azure, now lets deploy our vault into the Kubernetes cluster!</p><h3>Deploying vault with helm chart</h3><blockquote>Note: From this point, every time you see <strong><em>k </em></strong>in a command line example, assume it is a <strong><em>kubectl (</em></strong>I have a alias k=kubectl in my console<strong><em>)</em></strong></blockquote><p>Hashicorp now provides two official helm charts to be used in a vault infrastructure:</p><ul><li><a href="https://github.com/hashicorp/consul-helm">Consul helm chart</a> (will not be used in our environment — We will use <em>raft </em>encrypted storage)</li><li><a href="https://github.com/hashicorp/vault-helm">Vault helm chart</a> (not compatible with Helm 2)</li></ul><p>To deploy the chart, we need to:</p><ol><li>Add HashiCorp Helm repository to our system:</li></ol><pre>helm repo add hashicorp <a href="https://helm.releases.hashicorp.com/">https://helm.releases.hashicorp.com</a></pre><p>2. Fetch the chart, in order to edit the <em>values.yaml</em> file:</p><pre>helm fetch — untar hashicorp/vault</pre><p>3. Edit <em>values.yaml </em>to have:</p><ul><li>Unseal settings in place</li><li>Requests and limits set</li><li>PSP (PodSecurityPolicies) enabled</li><li>other customisations (as needed)</li></ul><p>The main section where we need to look into its related to use Azure Key Vault keys to unseal the vault, since its not included in file by default, so, in <em>ha → raft </em>section we need to add the following configuration block:</p><pre>seal &quot;azurekeyvault&quot; {<br>    tenant_id       = &quot;&lt;the tenant id you wrote down earlier&gt;&quot;<br>    client_id       = &quot;&lt;the client id you wrote down earlier&gt;&quot;<br>    client_secret   = &quot;&lt;the client secret you wrote down earlier&gt;&quot;<br>    vault_name      = &quot;&lt;the azure key vault name&gt;&quot;<br>    key_name        = &quot;&lt;the azure key vault key name&gt;&quot;<br>    subscription_id = &quot;&lt;the subscription id you wrote down earlier&gt;&quot;<br>    }</pre><p>Inside the <em>ha </em>section we also need to add the following code block, to enable the raft storage:</p><pre>dataStorage:<br>  enabled: true<br>  size: 10Gi</pre><p>So we will have a <em>ha → raft </em>section looking something like this:</p><pre># Run Vault in &quot;HA&quot; mode. There are no storage requirements unless audit log<br>  # persistence is required.  In HA mode Vault will configure itself to use Consul<br>  # for its storage backend.  The default configuration provided will work the Consul<br>  # Helm project by default.  It is possible to manually configure Vault to use a<br>  # different HA backend.<br>  ha:<br>    enabled: true<br>    replicas: 3</pre><pre>    # Set the api_addr configuration for Vault HA<br>    # See https://www.vaultproject.io/docs/configuration#api_addr<br>    # If set to null, this will be set to the Pod IP Address<br>    apiAddr: null</pre><pre>    # Enables Vault&#39;s integrated Raft storage.  Unlike the typical HA modes where<br>    # Vault&#39;s persistence is external (such as Consul), enabling Raft mode will create<br>    # persistent volumes for Vault to store data according to the configuration under server.dataStorage.<br>    # The Vault cluster will coordinate leader elections and failovers internally.<br>    raft:</pre><pre>      # Enables Raft integrated storage<br>      enabled: true<br>      # Set the Node Raft ID to the name of the pod<br>      setNodeId: false</pre><pre>      # Note: Configuration files are stored in ConfigMaps so sensitive data<br>      # such as passwords should be either mounted through extraSecretEnvironmentVars<br>      # or through a Kube secret.  For more information see:<br>      # https://www.vaultproject.io/docs/platform/k8s/helm/run#protecting-sensitive-vault-configurations<br>      config: |<br>        ui = true</pre><pre>        listener &quot;tcp&quot; {<br>          tls_disable = 1<br>          address = &quot;[::]:8200&quot;<br>          cluster_address = &quot;[::]:8201&quot;<br>        }</pre><pre>        storage &quot;raft&quot; {<br>          path = &quot;/vault/data&quot;<br>        }<br>        <br>        seal &quot;azurekeyvault&quot; {<br>          tenant_id       = &quot;&lt;the tenant id you wrote down earlier&gt;&quot;<br>          client_id       = &quot;&lt;the client id you wrote down earlier&gt;&quot;<br>          client_secret   = &quot;&lt;the client secret you wrote down earlier&gt;&quot;<br>          vault_name      = &quot;&lt;the azure key vault name&gt;&quot;<br>          key_name        = &quot;&lt;the azure key vault key name&gt;&quot;<br>          subscription_id = &quot;&lt;the subscription id you wrote down earlier&gt;&quot;<br>        }</pre><pre>        service_registration &quot;kubernetes&quot; {}<br>        <br>  dataStorage:<br>    enabled: true<br>    size: 10Gi</pre><h3>Why use <em>raft </em>storage ?</h3><p>The Integrated Storage backend is used to persist Vault’s data. Unlike other storage backends, Integrated Storage does not operate from a single source of data. Instead all the nodes in a Vault cluster will have a replicated copy of Vault’s data. Data gets replicated across all the nodes via the <a href="https://raft.github.io/">Raft Consensus Algorithm</a>.</p><ul><li><strong>High Availability</strong> — the Integrated Storage backend supports high availability.</li><li><strong>HashiCorp Supported</strong> — the Integrated Storage backend is officially supported by HashiCorp.</li></ul><h4>Challenge</h4><p>Vault supports many storage providers to persist its encrypted data (e.g. Consul, MySQL, DynamoDB, etc.). These providers require:</p><ul><li>Their own administration; increasing complexity and total administration.</li><li>Provider configuration to allow Vault as a client.</li><li>Vault configuration to connect to the provider as a client.</li></ul><h4>Solution</h4><p>Use Vault’s Integrated Storage to persist the encrypted data. The <a href="https://www.vaultproject.io/docs/configuration/storage/raft.html">integrated storage</a> has the following benefits:</p><ul><li>Integrated into Vault (reducing total administration)</li><li>All configuration within Vault</li><li>Supports failover and multi-cluster replication</li><li>Eliminates additional network requests</li><li>Lowers complexity when diagnosing issues (leading to faster time to recovery)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*JdtL6zWD5zroifp73scPUw.png" /></figure><h3>Deploy the chart</h3><p>After finishing the changes and customisations at <em>values.yaml</em> file, go to your console session, enter in vault directory and simply issue a:</p><pre>helm install -n &lt;target namespace&gt; &lt;deployment name — we’ve used vault&gt; hashicorp/vault -f values.yaml</pre><p>And you should receive something like this as command response:</p><pre>NAME: vault<br>LAST DEPLOYED: Fri Dec 11 08:42:04 2020<br>NAMESPACE: tooling<br>STATUS: deployed<br>REVISION: 1<br>TEST SUITE: None<br>NOTES:<br>Thank you for installing HashiCorp Vault!</pre><pre>Now that you have deployed Vault, you should look over the docs on using<br>Vault with Kubernetes available here:</pre><pre>https://www.vaultproject.io/docs/<br></pre><pre>Your release is named vault. To learn more about the release, try:</pre><pre>  $ helm status vault<br>  $ helm get manifest vault</pre><p>After the initial deploy, the vault its in <em>uninitialised </em>and<em> sealed </em>states.</p><h4>Initialise the vault</h4><p>To initialise the vault, we need to issue an:</p><pre>k -n &lt;target namespace&gt; exec -it vault-0 — vault operator init -n 1 -t 1</pre><p>And should receive something like this in response:</p><pre>Recovery Key 1: &lt;recovery key 1 - redacted&gt;<br>Recovery Key 2: &lt;recovery key 2 - redacted&gt;<br>Recovery Key 3: &lt;recovery key 3 - redacted&gt;<br>Recovery Key 4: &lt;recovery key 4 - redacted&gt;<br>Recovery Key 5: &lt;recovery key 5 - redacted&gt;</pre><pre>Initial Root Token: &lt;initial root token - redacted&gt;</pre><pre>Success! Vault is initialized</pre><pre>Recovery key initialized with 5 key shares and a key threshold of 3. Please<br>securely distribute the key shares printed above.</pre><pre>WARNING! -key-shares and -key-threshold is ignored when Auto Unseal is used.<br>Use -recovery-shares and -recovery-threshold instead.</pre><blockquote>Please write down and store in a secure way the recovery keys and the initial root token. If you loose the recovery keys you will <strong>NOT </strong>be able to recover your vault in case of problems</blockquote><p>In <strong>vault-0</strong> pod logs you should see something similar to:</p><pre>==&gt; Vault server configuration:<br>       Azure Environment: AzurePublicCloud<br>          Azure Key Name: vault-k8s-unsealer-key<br>        Azure Vault Name: vault-key-data<br>             Api Address: http://10.244.4.178:8200<br>                     Cgo: disabled<br>         Cluster Address: https://vault-0.vault-internal:8201<br>              Go Version: go1.14.7<br>              Listener 1: tcp (addr: &quot;[::]:8200&quot;, cluster address: &quot;[::]:8201&quot;, max_request_duration: &quot;1m30s&quot;, max_request_size: &quot;33554432&quot;, tls: &quot;disabled&quot;)<br>               Log Level: info<br>                   Mlock: supported: true, enabled: false<br>           Recovery Mode: false<br>                 Storage: raft (HA available)<br>                 Version: Vault v1.5.4<br>             Version Sha: 1a730771ec70149293efe91e1d283b10d255c6d1<br>==&gt; Vault server started! Log data will stream in below:<br>2020-12-11T08:42:54.638Z [INFO]  proxy environment: http_proxy= https_proxy= no_proxy=<br>2020-12-11T08:42:55.173Z [INFO]  core: stored unseal keys supported, attempting fetch<br>2020-12-11T08:42:55.173Z [WARN]  failed to unseal core: error=&quot;stored unseal keys are supported, but none were found&quot;<br>2020-12-11T08:43:00.173Z [INFO]  core: stored unseal keys supported, attempting fetch<br>2020-12-11T08:43:00.173Z [WARN]  failed to unseal core: error=&quot;stored unseal keys are supported, but none were found&quot;<br>2020-12-11T08:43:00.331Z [INFO]  core.autoseal: seal configuration missing, but cannot check old path as core is sealed: seal_type=recovery<br>2020-12-11T08:43:05.173Z [INFO]  core: stored unseal keys supported, attempting fetch<br>2020-12-11T08:43:05.173Z [WARN]  failed to unseal core: error=&quot;stored unseal keys are supported, but none were found&quot;<br>2020-12-11T08:43:05.332Z [INFO]  core.autoseal: seal configuration missing, but cannot check old path as core is sealed: seal_type=recovery<br>2020-12-11T08:43:10.174Z [INFO]  core: stored unseal keys supported, attempting fetch<br>2020-12-11T08:43:10.174Z [WARN]  failed to unseal core: error=&quot;stored unseal keys are supported, but none were found&quot;<br>2020-12-11T08:43:10.240Z [INFO]  core.autoseal: seal configuration missing, but cannot check old path as core is sealed: seal_type=recovery<br>2020-12-11T08:43:15.230Z [INFO]  core: stored unseal keys supported, attempting fetch<br>2020-12-11T08:43:15.230Z [WARN]  failed to unseal core: error=&quot;stored unseal keys are supported, but none were found&quot;<br>2020-12-11T08:43:15.240Z [INFO]  core.autoseal: seal configuration missing, but cannot check old path as core is sealed: seal_type=recovery<br>2020-12-11T08:43:19.241Z [WARN]  core: stored keys supported on init, forcing shares/threshold to 1<br>2020-12-11T08:43:19.241Z [INFO]  core: security barrier not initialized<br>2020-12-11T08:43:19.257Z [INFO]  storage.raft: initial configuration: index=1 servers=&quot;[{Suffrage:Voter ID:3b7e498a-9c3c-89e4-c4d5-83f0e589f4e3 Address:vault-0.vault-internal:8201}]&quot;<br>2020-12-11T08:43:19.257Z [INFO]  storage.raft: entering follower state: follower=&quot;Node at 3b7e498a-9c3c-89e4-c4d5-83f0e589f4e3 [Follower]&quot; leader=<br>2020-12-11T08:43:20.243Z [INFO]  core.autoseal: seal configuration missing, but cannot check old path as core is sealed: seal_type=recovery<br>2020-12-11T08:43:24.674Z [WARN]  storage.raft: heartbeat timeout reached, starting election: last-leader=<br>2020-12-11T08:43:24.674Z [INFO]  storage.raft: entering candidate state: node=&quot;Node at 3b7e498a-9c3c-89e4-c4d5-83f0e589f4e3 [Candidate]&quot; term=2<br>2020-12-11T08:43:24.690Z [INFO]  storage.raft: election won: tally=1<br>2020-12-11T08:43:24.690Z [INFO]  storage.raft: entering leader state: leader=&quot;Node at 3b7e498a-9c3c-89e4-c4d5-83f0e589f4e3 [Leader]&quot;<br>2020-12-11T08:43:24.736Z [INFO]  core: security barrier initialized: stored=1 shares=1 threshold=1<br>2020-12-11T08:43:24.873Z [INFO]  core: post-unseal setup starting<br>2020-12-11T08:43:24.950Z [INFO]  core: loaded wrapping token key<br>2020-12-11T08:43:24.951Z [INFO]  core: successfully setup plugin catalog: plugin-directory=<br>2020-12-11T08:43:24.951Z [INFO]  core: no mounts; adding default mount table<br>2020-12-11T08:43:25.049Z [INFO]  core: successfully mounted backend: type=cubbyhole path=cubbyhole/<br>2020-12-11T08:43:25.049Z [INFO]  core: successfully mounted backend: type=system path=sys/<br>2020-12-11T08:43:25.049Z [INFO]  core: successfully mounted backend: type=identity path=identity/<br>2020-12-11T08:43:25.330Z [INFO]  core: successfully enabled credential backend: type=token path=token/<br>2020-12-11T08:43:25.330Z [INFO]  core: restoring leases<br>2020-12-11T08:43:25.330Z [INFO]  rollback: starting rollback manager<br>2020-12-11T08:43:25.331Z [INFO]  expiration: lease restore complete<br>2020-12-11T08:43:25.337Z [INFO]  core.autoseal: seal configuration missing, but cannot check old path as core is sealed: seal_type=recovery<br>2020-12-11T08:43:25.362Z [INFO]  identity: entities restored<br>2020-12-11T08:43:25.363Z [INFO]  identity: groups restored<br>2020-12-11T08:43:25.382Z [WARN]  core: post-unseal upgrade seal keys failed: error=&quot;no recovery key found&quot;<br>2020-12-11T08:43:25.382Z [INFO]  core: usage gauge collection is disabled<br>2020-12-11T08:43:25.395Z [INFO]  core: post-unseal setup complete<br>2020-12-11T08:43:25.502Z [INFO]  core: root token generated<br>2020-12-11T08:43:25.561Z [INFO]  core: pre-seal teardown starting<br>2020-12-11T08:43:25.561Z [INFO]  rollback: stopping rollback manager<br>2020-12-11T08:43:25.561Z [INFO]  core: pre-seal teardown complete<br>2020-12-11T08:43:25.606Z [INFO]  core: stored unseal keys supported, attempting fetch<br>2020-12-11T08:43:25.668Z [INFO]  core.cluster-listener.tcp: starting listener: listener_address=[::]:8201<br>2020-12-11T08:43:25.668Z [INFO]  core.cluster-listener: serving cluster requests: cluster_listen_address=[::]:8201<br>2020-12-11T08:43:25.674Z [INFO]  storage.raft: initial configuration: index=1 servers=&quot;[{Suffrage:Voter ID:3b7e498a-9c3c-89e4-c4d5-83f0e589f4e3 Address:vault-0.vault-internal:8201}]&quot;<br>2020-12-11T08:43:25.674Z [INFO]  core: vault is unsealed<br>2020-12-11T08:43:25.674Z [INFO]  core: entering standby mode<br>2020-12-11T08:43:25.674Z [INFO]  storage.raft: entering follower state: follower=&quot;Node at vault-0.vault-internal:8201 [Follower]&quot; leader=<br>2020-12-11T08:43:25.741Z [INFO]  core: unsealed with stored keys: stored_keys_used=1<br>2020-12-11T08:43:25.741Z [WARN]  core: attempted unseal with stored keys, but vault is already unsealed<br>2020-12-11T08:43:33.146Z [WARN]  storage.raft: heartbeat timeout reached, starting election: last-leader=<br>2020-12-11T08:43:33.146Z [INFO]  storage.raft: entering candidate state: node=&quot;Node at vault-0.vault-internal:8201 [Candidate]&quot; term=3<br>2020-12-11T08:43:33.163Z [INFO]  storage.raft: election won: tally=1<br>2020-12-11T08:43:33.163Z [INFO]  storage.raft: entering leader state: leader=&quot;Node at vault-0.vault-internal:8201 [Leader]&quot;<br>2020-12-11T08:43:33.186Z [INFO]  core: acquired lock, enabling active operation<br>2020-12-11T08:43:33.312Z [INFO]  core: post-unseal setup starting<br>2020-12-11T08:43:33.330Z [INFO]  core: loaded wrapping token key<br>2020-12-11T08:43:33.330Z [INFO]  core: successfully setup plugin catalog: plugin-directory=<br>2020-12-11T08:43:33.330Z [INFO]  core: successfully mounted backend: type=system path=sys/<br>2020-12-11T08:43:33.330Z [INFO]  core: successfully mounted backend: type=identity path=identity/<br>2020-12-11T08:43:33.330Z [INFO]  core: successfully mounted backend: type=cubbyhole path=cubbyhole/<br>2020-12-11T08:43:33.331Z [INFO]  core: successfully enabled credential backend: type=token path=token/<br>2020-12-11T08:43:33.332Z [INFO]  core: restoring leases<br>2020-12-11T08:43:33.332Z [INFO]  rollback: starting rollback manager<br>2020-12-11T08:43:33.332Z [INFO]  expiration: lease restore complete<br>2020-12-11T08:43:33.332Z [INFO]  identity: entities restored<br>2020-12-11T08:43:33.332Z [INFO]  identity: groups restored<br>2020-12-11T08:43:33.359Z [INFO]  core: usage gauge collection is disabled<br>2020-12-11T08:43:33.375Z [INFO]  core: post-unseal setup complete</pre><p>In log snippet above, you can see starting at line 32 the process of vault being initialised and automatic unsealed, thanks to our MS Azure Key Vault configuration applied to deployment.</p><h4>Join additional pods to cluster</h4><p>After the vault has been successfully initialised and unsealed, we must joint the additional nodes to the cluster, we can achieve it easily issuing in the console a:</p><pre>k -n &lt;target namespace&gt; exec -it vault-[N] — vault operator raft join <a href="http://vault-0.vault-internal:8200/">http://vault-0.vault-internal:8200</a></pre><p>Where:</p><ul><li>&lt;target namespace&gt; will be the namespace where our vault its installed (in my example its installed at <strong>tooling </strong>namespace in tooling cluster)</li><li>vault-[N] will be the pod replica name where we want to run the command</li><li>in my environment we’ve spawned 3 replicas, so we need to run the command to <strong>vault-1</strong> and <strong>vault-2</strong> pods</li><li><a href="http://vault-0.vault-internal:8200/">http://vault-0.vault-internal:8200</a> its the default name/domain deployed via our values.yaml file, if you have changed it there, please adjust the command accordingly.</li></ul><p>In vault-[N] pod logs you should see something similar to:</p><pre>2020-12-11T08:47:10.076Z [INFO]  core: attempting to join possible raft leader node: leader_addr=http://vault-0.vault-internal:8200<br>2020-12-11T08:47:10.230Z [INFO]  core.cluster-listener.tcp: starting listener: listener_address=[::]:8201<br>2020-12-11T08:47:10.231Z [INFO]  core.cluster-listener: serving cluster requests: cluster_listen_address=[::]:8201<br>2020-12-11T08:47:10.246Z [WARN]  core.cluster-listener: no TLS config found for ALPN: ALPN=[raft_storage_v1]<br>2020-12-11T08:47:10.247Z [INFO]  storage.raft: initial configuration: index=1 servers=&quot;[{Suffrage:Voter ID:3b7e498a-9c3c-89e4-c4d5-83f0e589f4e3 Address:vault-0.vault-internal:8201} {Suffrage:Voter ID:9984ccf4-29de-e9fd-6f12-b34e60b9c804 Address:vault-1.vault-internal:8201} {Suffrage:Voter ID:296ce341-ad99-5d60-1a04-052dee3ebf57 Address:vault-2.vault-internal:8201}]&quot;<br>2020-12-11T08:47:10.247Z [INFO]  core: successfully joined the raft cluster: leader_addr=http://vault-0.vault-internal:8200<br>2020-12-11T08:47:10.247Z [INFO]  storage.raft: entering follower state: follower=&quot;Node at vault-2.vault-internal:8201 [Follower]&quot; leader=<br>2020-12-11T08:47:10.573Z [WARN]  storage.raft: failed to get previous log: previous-index=39 last-index=1 error=&quot;log not found&quot;<br>2020-12-11T08:47:10.840Z [INFO]  core: stored unseal keys supported, attempting fetch<br>2020-12-11T08:47:10.856Z [WARN]  core: cluster listener is already started<br>2020-12-11T08:47:10.856Z [INFO]  core: vault is unsealed<br>2020-12-11T08:47:10.857Z [INFO]  core: entering standby mode<br>2020-12-11T08:47:10.964Z [INFO]  core: unsealed with stored keys: stored_keys_used=1</pre><p>Confirming the pod was able to join the cluster and unseal it own copy of the vault automatically, using our MS Azure Key Vault definitions.</p><h3>Adding GitLab integration</h3><h3>How it works</h3><p>Each job has JSON Web Token (JWT) provided as environment variable named CI_JOB_JWT. This JWT can be used to authenticate with Vault using the <a href="https://www.vaultproject.io/docs/auth/jwt#jwt-authentication">JWT Auth</a> method.</p><p>The JWT’s payload looks like this:</p><pre>{<br>  &quot;jti&quot;: &quot;c82eeb0c-5c6f-4a33-abf5-4c474b92b558&quot;, # Unique identifier for this token<br>  &quot;iss&quot;: &quot;gitlab.example.com&quot;,                   # Issuer, the domain of your GitLab instance<br>  &quot;iat&quot;: 1585710286,                             # Issued at<br>  &quot;nbf&quot;: 1585798372,                             # Not valid before<br>  &quot;exp&quot;: 1585713886,                             # Expire at<br>  &quot;sub&quot;: &quot;job_1212&quot;,                             # Subject (job id)<br>  &quot;namespace_id&quot;: &quot;1&quot;,                           # Use this to scope to group or user level namespace by id<br>  &quot;namespace_path&quot;: &quot;mygroup&quot;,                   # Use this to scope to group or user level namespace by path<br>  &quot;project_id&quot;: &quot;22&quot;,                            #<br>  &quot;project_path&quot;: &quot;mygroup/myproject&quot;,           #<br>  &quot;user_id&quot;: &quot;42&quot;,                               # Id of the user executing the job<br>  &quot;user_email&quot;: &quot;myuser@example.com&quot;,            # Email of the user executing the job<br>  &quot;pipeline_id&quot;: &quot;1212&quot;,                         #<br>  &quot;job_id&quot;: &quot;1212&quot;,                              #<br>  &quot;ref&quot;: &quot;auto-deploy-2020-04-01&quot;,               # Git ref for this job<br>  &quot;ref_type&quot;: &quot;branch&quot;,                          # Git ref type, branch or tag<br>  &quot;ref_protected&quot;: &quot;true&quot;                        # true if this git ref is protected, false otherwise<br>}</pre><p>The JWT is encoded by using RS256 and signed with a dedicated private key. The expire time for the token will be set to job’s timeout, if specified, or 5 minutes if it is not. The key used to sign this token may change without any notice. In such case retrying the job will generate new JWT using the current signing key.</p><p>You can use this JWT and your instance’s JWKS endpoint (https://gitlab.mycustomer.io/-/jwks) to authenticate with a Vault server that is configured to allow the JWT Authentication method for authentication.</p><h3>Enabling jwt authentication method in vault</h3><p>In order to configure the authentication, we will need to run commands inside one of the vault pods, to connect to pod, use the kubectl commandlet below:</p><pre>k -n &lt;target namespace&gt; exec -it vault-[N] /bin/sh</pre><p>And in the command shell displayed, login into the vault and enable the jwt authentication method with:</p><p><strong>Get a shell in the vault pod:</strong></p><pre>k -n tooling exec -it vault-0 /bin/sh</pre><p><strong>Login in the vault </strong>(using the root token the install provided to you earlier):</p><pre>/ $ vault login<br>Token (will be hidden):<br>Success! You are now authenticated. The token information displayed below<br>is already stored in the token helper. You do NOT need to run “vault login”<br>again. Future Vault requests will automatically use this token.</pre><pre>Key Value</pre><pre>— — — — — — — — — — — — — -</pre><pre>token &lt;root token&gt;<br>token_accessor &lt;redacted&gt;<br>token_duration ∞<br>token_renewable false<br>token_policies [“root”]<br>identity_policies []<br>policies [“root”]</pre><p><strong>And enable authentication using JWT:</strong></p><pre>/ $ vault auth enable jwt<br>Success! Enabled jwt auth method at: jwt/</pre><p>Now, lets create our first policy, which will give us permission to read the secrets stored in the following path: secret/customer/dev/*</p><pre>/ $ vault policy write customer-dev — &lt;&lt;EOF</pre><pre>&gt; path “secret/customer/dev/*” {<br>&gt; capabilities = [ “read” ]<br>&gt; }<br>&gt; EOF<br>Success! Uploaded policy: customer-dev</pre><p>We also need to create an role, which links the JWT with the policy we just created:</p><pre>/ $ vault write auth/jwt/role/customer-dev — &lt;&lt;EOF</pre><pre>&gt; {<br>&gt; “role_type”: “jwt”,<br>&gt; “policies”: [“customer-dev”],<br>&gt; “token_explicit_max_ttl”: 60,<br>&gt; “user_claim”: “user_email”,<br>&gt; “bound_claims”: {<br>&gt; “project_id”: “5919”,<br>&gt; “ref”: “dev”,<br>&gt; “ref_type”: “branch”<br>&gt; }<br>&gt; }<br>&gt; EOF<br>/ $</pre><p><strong>Important informations about the command above:</strong></p><ul><li>It don’t give any confirmation message, but the role has been created</li><li>The role created above only applies to a single project (<strong>5919</strong> — test-api in our case, limited by project_id property)</li><li>The role created above only applies to <strong>dev</strong> branch (properties ref and ref_type)</li><li><a href="https://www.vaultproject.io/api/auth/jwt#token_explicit_max_ttl">token_explicit_max_ttl</a> specifies that the token issued by Vault, upon successful authentication, has a hard lifetime limit of 60 seconds.</li><li><a href="https://www.vaultproject.io/api/auth/jwt#user_claim">user_claim</a> specifies the name for the Identity alias created by Vault upon a successful login.</li><li><a href="https://www.vaultproject.io/api-docs/auth/jwt#bound_claims_type">bound_claims_type</a> configures the interpretation of the bound_claims values. If set to glob, the values will be interpreted as globs, with * matching any number of characters.</li></ul><p>For a production environment, more wide policies should be taken in account (maybe one policy by branch type).</p><p>In <a href="https://www.vaultproject.io/api-docs/auth/jwt">documentation page about jwt authentication</a>, we have the following:</p><h3>bound_claims</h3><blockquote>(map: &lt;optional&gt;) — If set, a map of claims (keys) to match against respective claim values (values). The expected value may be a single string or a list of strings. The interpretation of the bound claim values is configured with bound_claims_type. Keys support <a href="https://www.vaultproject.io/docs/auth/jwt#claim-specifications-and-json-pointer">JSON pointer</a> syntax for referencing claims.</blockquote><h3>bound_claims_type</h3><blockquote>(string: “string”) — Configures the interpretation of the bound_claims values. If “string” (the default), the values will treated as string literals and must match exactly. If set to “glob”, the values will be interpreted as globs, with * matching any number of characters.</blockquote><h3>groups_claim</h3><blockquote>(string: &lt;optional&gt;) — The claim to use to uniquely identify the set of groups to which the user belongs; this will be used as the names for the Identity group aliases created due to a successful login. The claim value must be a list of strings. Supports <a href="https://www.vaultproject.io/docs/auth/jwt#claim-specifications-and-json-pointer">JSON pointer</a> syntax for referencing claims.</blockquote><h3><strong>claim_mappings</strong></h3><blockquote>(map: &lt;optional&gt;) — If set, a map of claims (keys) to be copied to specified metadata fields (values). Keys support <a href="https://www.vaultproject.io/docs/auth/jwt#claim-specifications-and-json-pointer">JSON pointer</a> syntax for referencing claims.</blockquote><p>Now we need to configure the JWT authentication method:</p><pre>/ $ vault write auth/jwt/config \</pre><pre>&gt; jwks_url=”https://gitlab.mycustomer.io/-/jwks&quot; \</pre><pre>&gt; bound_issuer=”gitlab.mycustomer.io”<br>Success! Data written to: auth/jwt/config</pre><p>The <a href="https://www.vaultproject.io/api/auth/jwt#inlinecode-bound_issuer">bound_issuer</a> parameter specifies that only a JWT with the issuer (that is, the iss claim) set to gitlab.mycustomer.io can use this method to authenticate, and that the JWKS endpoint (https://gitlab.mycustomer.io/-/jwks) should be used to validate the token.</p><h3>Checking settings in vault ui</h3><p>To access to vault-ui, we need to set a port-forward in our machine, to do that, issue the following command in your console session:</p><pre>k -n tooling port-forward svc/vault 8200:8200</pre><p>And go to <a href="http://localhost:8200/">http://localhost:8200</a> in your browser to connect to vault-ui:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*ZEjoyupLC-QPex11_3OcdA.png" /></figure><p>In order to access the vault-ui using the root token, you <strong>MUST</strong> use the local direct connection, if you try to do that using a external connection (via a URL using a ingress for example) you will not able to connect to it.</p><p>After logging in, go to <strong><em>Policies</em></strong> and <strong><em>Access</em></strong> panes, and confirm the information we entered via console using vault command is there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEIsLGEcAavOFXG8-09uag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1c3kBSX3h68DXlK-0vojA.png" /></figure><h3>Creating our first secret</h3><p>Now we already have access to vault-ui, lets create a simple secret, which will be used later to validate the GitLab integration via JWT.</p><p>To do that, go to <strong><em>Secrets </em></strong>pane in vault-ui and click in “Enable new engine +” button at right side of the panel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApQJ1TOR9BEq8ibNltLlbQ.png" /></figure><p>In “<strong>Enable a Secrets Engine</strong>”, choose “<strong>KV</strong>” in Generic engines section and click “<strong>Next</strong>” to continue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*McShBB5POcoHhHqS_nzI_g.png" /></figure><p>In “<strong>Enable KV Secrets Engine</strong>”<strong> </strong>details page, set the path to “<strong>secret/customer/dev</strong>”<strong> </strong>and click in “Enable Engine” to finish the creation of the KV secrets engine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UINookkdroSIZeMcqO8WlQ.png" /></figure><p>Now, lets create our first secret, click in “<strong>Create secret +</strong>” button at the right side of the pane to start the creation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zv4kstroy5Smia2WSYO0YQ.png" /></figure><p>The path for our secret (for a organisation sake matter) should be the name of the API which this secret will serve to, in this case, enter “<strong>test</strong>” as the path, and in “<strong>Version data</strong>” section, enter the name of the secret (key) and the value (value) it should have secretly stored. After that click in “<strong>Save</strong>” to finish the secret creation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wn0FLlUH77wvbwbIcQEMGw.png" /></figure><p>And finally the <strong><em>secret/customer/dev/test</em></strong> secret section should look like this now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2a-7UrKoqFB-BBk2GYENBg.png" /></figure><h3>Testing vault secrets in GitLab</h3><p>Now, we must go to <strong>.gitlab-ci.yml</strong> file on <strong>test-api</strong> branch, and we can test the success of implementation with this example code:</p><pre>Read Secrets:<br>  stage: read_secrets<br>  image: vault:1.5.4<br>  script:<br>    # Check job&#39;s ref name<br>    - echo $CI_COMMIT_REF_NAME<br>    # and is this ref protected<br>    - echo $CI_COMMIT_REF_PROTECTED<br>    # Vault&#39;s address can be provided here or as CI variable<br>    - export VAULT_ADDR=https://vault.mycustomer.io<br>    # Authenticate and get token. Token expiry time and other properties can be configured<br>    # when configuring JWT Auth - https://www.vaultproject.io/api/auth/jwt#parameters-1<br>    - export VAULT_TOKEN=&quot;$(vault write -field=token auth/jwt/login role=customer-dev jwt=$CI_JOB_JWT)&quot;<br>    # Now use the VAULT_TOKEN to read the secret and store it in an environment variable<br>    - export PASSWORD=&quot;$(vault kv get -field=password secret/customer/dev/test)&quot;<br>    # Use the secret<br>    - echo $PASSWORD</pre><p>Notes about the config snippet above:</p><ul><li>In line <strong>10</strong> we set the URL where the vault client should go to fetch the data</li><li>In line <strong>13 </strong>we authenticate using the <strong>JWT </strong>authentication method, with our role created previously (<strong>customer-dev</strong>) and an JWT token created by default by GitLab (which its stored in the default variable <strong><em>CI_JOB_JWT</em></strong>)</li><li>In line <strong>15</strong>, after the authentication using the JWT token, we read the field <strong>password</strong> inside the path <strong>secret/customer/dev/test</strong></li><li>Finally in line <strong>17</strong> we do a simply ECHO command, to show we had success obtaining the data from vault</li></ul><p>If we submit this code for an pipeline execution, we should receive something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2RP2ZOcaPV6OqP4D0CUeg.png" /></figure><p>Note the value for <strong>$PASSWORD</strong> variable being shown, after got fetched from vault.</p><h3>Adding kubernetes integration/authentication</h3><p>In order to use vault with kubernetes, the best approach its use the kubernetes certificates to authenticate against vault, to do it, we need to:</p><ul><li>Enable kubernetes authentication method in vault cluster</li><li>Create initial kubernetes authentication configuration in vault</li><li>Create policy</li><li>Create role</li><li>Add fields in deployment configuration to authenticate with vault</li><li>Change existing fields in deployment configuration to fetch data from vault instead of secrets/configmaps</li></ul><h3>Enable kubernetes authentication method in vault cluster</h3><p>To start the configuration, we need to execute a session in our vault cluster and enable the kubernetes auth method, that could be done with:</p><p>Get shell session into vault pod:</p><pre>k -n &lt;target namespace&gt; exec -it vault-[N] /bin/sh</pre><p>Login into vault with root token:</p><pre>/ $ vault login<br>Token (will be hidden):<br>Success! You are now authenticated. The token information displayed below<br>is already stored in the token helper. You do NOT need to run “vault login”<br>again. Future Vault requests will automatically use this token.</pre><pre>Key Value</pre><pre>token &lt;root token got during vault configuration&gt;<br>token_accessor &lt;redacted&gt;<br>token_duration ∞<br>token_renewable false<br>token_policies [“root”]<br>identity_policies []<br>policies [“root”]</pre><p>Enable kubernetes authentication method:</p><pre>/ $ vault auth enable kubernetes<br>Success! Enabled kubernetes auth method at: kubernetes/</pre><h3>Create service account, secret and role binding to be used by vault</h3><p>To each namespace where we want to use the vault, we must create an secret and a ClusterRoleBinding (in my customer case we will use an existing service account) in order to fetch the data from cluster and use it to authenticate against vault.</p><pre>---<br>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: vault-auth<br>  namespace: &lt;target namespace&gt;<br>  annotations:<br>    kubernetes.io/service-account.name: &lt;target service account&gt;<br>type: kubernetes.io/service-account-token<br>---<br>apiVersion: rbac.authorization.k8s.io/v1beta1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: role-tokenreview-binding-&lt;target namespace&gt;<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: ClusterRole<br>  name: system:auth-delegator<br>subjects:<br>  - kind: ServiceAccount<br>    name: &lt;target service account&gt;<br>    namespace: &lt;target namespace&gt;</pre><h3>Create initial kubernetes authentication configuration in vault</h3><p>You should install vault package in your local machine, to be easier to complete the following steps, it can be installed with: brew install vault</p><p>Vault accepts service token from any client within the Kubernetes cluster. During authentication, Vault verifies that the service account token is valid by querying a configured Kubernetes endpoint. To configure it correctly requires capturing the JSON web token (JWT) for the service account, the Kubernetes CA certificate, and the Kubernetes host URL.</p><p>First, get the JSON web token (JWT) for this service account.</p><pre>TOKEN_REVIEW_JWT=$(kubectl -n &lt;target namespace&gt; get secret vault-auth -o go-template=’{{ .data.token }}’ | base64 — decode)</pre><p>Next, retrieve the Kubernetes CA certificate:</p><pre>KUBE_CA_CERT=$(kubectl config view — raw — minify — flatten -o jsonpath=’{.clusters[].cluster.certificate-authority-data}’ | base64 — decode)</pre><p>Next, retrieve the Kubernetes host URL:</p><pre>KUBE_HOST=$(kubectl config view — raw — minify — flatten -o jsonpath=’{.clusters[].cluster.server}’)</pre><p>Finally, configure the Kubernetes authentication method to use the service account token, the location of the Kubernetes host, and its certificate:</p><pre>vault write auth/kubernetes/config \<br>        token_reviewer_jwt=&quot;$TOKEN_REVIEW_JWT&quot; \<br>        kubernetes_host=&quot;$KUBE_HOST&quot; \<br>        kubernetes_ca_cert=&quot;$KUBE_CA_CERT&quot;</pre><h3>Create policy</h3><p>For a client to access the secret data defined, at secret/customer/dev/common, requires that the read capability be granted for the path secret/customer/dev/common. This is an example of a <a href="https://www.vaultproject.io/docs/concepts/policies.html">policy</a>. A policy defines a set of capabilities.</p><p>Write out the policy named dev-common that enables the read capability for secrets at path secret/customer/dev/common:</p><pre>/ $ vault policy write dev-common — &lt;&lt;EOF<br> path “secret/customer/dev/common” {<br> capabilities = [“read”]<br> }<br>EOF<br>Success! Uploaded policy: dev-common</pre><h3>Create role</h3><p>To apply this policy requires the authentication engine to define a role. A role binds policies and environment parameters together to create a login for the web application.</p><p>Create a Kubernetes authentication role, named dev-common, that connects the Kubernetes service account name and dev-common policy:</p><pre>/ $ vault write auth/kubernetes/role/dev-common \<br> bound_service_account_names=customer-aks-dev-user \<br> bound_service_account_namespaces=customer-aks-dev \<br> policies=dev-common \<br> ttl=24h<br>Success! Data written to: auth/kubernetes/role/dev-common</pre><p>The role connects the Kubernetes service account <strong><em>customer-aks-dev-user</em></strong> and namespace <strong><em>customer-aks-dev</em></strong> with the Vault policy <strong><em>dev-common</em></strong>. The tokens returned after authentication are valid for 24 hours.</p><h3>Install vault Agent Injector service in target namespace</h3><p>The Vault Helm chart is able to install only the Vault Agent Injector service. So lets install the latest version of the Vault server running in external mode:</p><pre>helm install -n &lt;target namespace&gt; vault hashicorp/vault \<br>    --set &quot;injector.externalVaultAddr=https://vault.mycustomer.io&quot;</pre><p>The Vault Agent Injector pod is deployed in the target namespace.</p><p>Now we should have in the target namespace a pod called vault-agent-injector-xxxxxxxx-xxxx, wait it reports that it is running and ready (1/1).</p><h3>Inject secrets into deployments</h3><p>The Vault Agent Injector only modifies a deployment if it contains a specific set of annotations. An existing deployment may have its definition patched to include the necessary annotations.</p><p>Example of annotations needed to deployment have secrets injected into it:</p><pre>spec:<br>  template:<br>    metadata:<br>      annotations:<br>        vault.hashicorp.com/agent-inject: &quot;true&quot;<br>        vault.hashicorp.com/role: &quot;dev-common&quot;<br>        vault.hashicorp.com/agent-inject-secret-credentials.txt: &quot;secret/customer/dev/common&quot;</pre><p>These <a href="https://www.vaultproject.io/docs/platform/k8s/injector#secrets-via-annotations">annotations</a> define a partial structure of the deployment schema and are prefixed with vault.hashicorp.com.</p><ul><li><a href="https://learn.hashicorp.com/tutorials/vault/kubernetes-external-vault#agent-inject">agent-inject</a></li><li>enables the Vault Agent Injector service</li><li><a href="https://learn.hashicorp.com/tutorials/vault/kubernetes-external-vault#role">role</a></li><li>is the Vault Kubernetes authentication role</li><li><a href="https://learn.hashicorp.com/tutorials/vault/kubernetes-external-vault#agent-inject-secret-filepath">agent-inject-secret-FILEPATH</a></li><li>prefixes the path of the file, credentials.txt written to the /vault/secrets directory. The value is the path to the secret defined in Vault.</li></ul><p>With this example above, the Vault Agent Injector service automatically writes the secrets to our pod at the filepath /vault/secrets/credentials.txt.</p><p>A complete example for a deployment:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: orgchart<br>  labels:<br>    app: orgchart<br>spec:<br>  selector:<br>    matchLabels:<br>      app: orgchart<br>  replicas: 1<br>  template:<br>    metadata:<br>      annotations:<br>        vault.hashicorp.com/agent-inject: &quot;true&quot;<br>        vault.hashicorp.com/role: &quot;dev-common&quot;<br>        vault.hashicorp.com/agent-inject-secret-config: &quot;secret/customer/dev/common&quot;<br>        vault.hashicorp.com/agent-inject-template-config: |<br>          {{ with secret &quot;secret/customer/dev/common&quot; -}}<br>            export AAD_TENANT_ID=&quot;{{ .Data.data.AAD_TENANT_ID }}&quot;<br>            export ECO_IAM_KEYS_URL=&quot;{{ .Data.data.ECO_IAM_KEYS_URL }}&quot;<br>          {{- end }}<br>      labels:<br>        app: orgchart<br>    spec:<br>      automountServiceAccountToken: true<br>      serviceAccountName: customer-aks-dev-user<br>      containers:<br>        - name: orgchart<br>          image: jweissig/app:0.0.1</pre><h3>Other approaches — Reading secrets from springboot directly</h3><p>Currently its tested and working in kubernetes, but with the injector, we save the secrets to a local file in the pod, and after that those values must be exported as environment variables.</p><p>If our final goal it’s maintain the secrets… secret! We should not expose it like that.</p><p>In <a href="http://spring.io/">spring.io</a> I’ve found some examples of how to implement the vault access directly from application, which solve this problem:</p><ul><li><a href="https://spring.io/guides/gs/accessing-vault/">https://spring.io/guides/gs/accessing-vault/</a></li><li><a href="https://spring.io/blog/2016/06/24/managing-secrets-with-vault">https://spring.io/blog/2016/06/24/managing-secrets-with-vault</a></li></ul><p>If we decide to go in that direction, we must add the code in all API’s (looks like a small — but repetitive — effort) and discuss about the secret structure organisation inside the vault (next topic).</p><h3>References and links</h3><p>To write and &quot;glue&quot; up this article together, I&#39;ve need to browse a lot and sum up several references, which as listed below:</p><ul><li><a href="https://docs.gitlab.com/ee/ci/examples/authenticating-with-hashicorp-vault/">https://docs.gitlab.com/ee/ci/examples/authenticating-with-hashicorp-vault/</a></li><li><a href="https://dev.to/gateixeira/unseal-your-vault-instance-with-azure-key-vault-the-definitive-guide-1ijd">https://dev.to/gateixeira/unseal-your-vault-instance-with-azure-key-vault-the-definitive-guide-1ijd</a></li><li><a href="https://www.vaultproject.io/docs/platform/k8s/helm/run#architecture">https://www.vaultproject.io/docs/platform/k8s/helm/run#architecture</a></li><li><a href="https://www.vaultproject.io/docs/platform/k8s/helm/run">https://www.vaultproject.io/docs/platform/k8s/helm/run</a></li><li><a href="https://learn.hashicorp.com/tutorials/vault/kubernetes-minikube">https://learn.hashicorp.com/tutorials/vault/kubernetes-minikube</a></li><li><a href="https://learn.hashicorp.com/tutorials/vault/kubernetes-external-vault">https://learn.hashicorp.com/tutorials/vault/kubernetes-external-vault</a></li><li><a href="https://learn.hashicorp.com/tutorials/vault/kubernetes-sidecar">https://learn.hashicorp.com/tutorials/vault/kubernetes-sidecar</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=241e888ac94e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reducing k8s cluster costs with preemptible VM's]]></title>
            <link>https://andersonsleite.medium.com/reducing-k8s-cluster-costs-with-preemptible-vms-91e379bf2c3a?source=rss-b5a2428d26a------2</link>
            <guid isPermaLink="false">https://medium.com/p/91e379bf2c3a</guid>
            <category><![CDATA[finops]]></category>
            <category><![CDATA[cost-management]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Anderson Leite]]></dc:creator>
            <pubDate>Wed, 10 Feb 2021 10:05:58 GMT</pubDate>
            <atom:updated>2021-02-10T13:21:23.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*UvvGGv4jjL81TLrPaeTi0g.jpeg" /></figure><h3>First of all: What is a preemptible VM?</h3><p>It&#39;s a VM instance like any other (in computing resources usage way), but this type of VM take advantage of unused resources of the cloud provider to run.</p><p>Since it take advantage of unused resources (which will be represent costs to the cloud provider anyway) cloud providers turn it way cheaper of a normal VM as a &quot;incentive&quot; to use it (in GCP for instance it could be up to 80% cheaper!).</p><p>Looks wonderful and your manager its now screaming at you because your infrastructure is not using it yet. Ok, calm down, count to 10, take a deep breath and now let me tell you that (of course) have a bitter side: Again using GCP as example, this type of VM&#39;s will live <strong><em>up to</em></strong><em> </em>24 hours.</p><p>Note I&#39;ve said <strong><em>up to</em></strong><em> 24 hours</em>, not 24 hours only, why? Because since it take advantage of unused resources in the specific geographic/datacenter zone the VM is hosted, if the cloud provider need computing power, well, your VM will got be killed, just like that.</p><p>So, before we talk about save some money, lets understand how this type of machine are different from a regular VM and which strategies we can put in place to use it and don&#39;t have our infra killed and unavailable if resources are needed by the cloud provider in that zone.</p><h3>Preemptible VM Pricing</h3><p>Pricing is fixed, not variable, and you can view the preemptible price alongside the on demand prices in Google’s compute pricing list and/or pricing calculator. Prices are 70–80% off on demand, and upward of 50% off even compared to a <a href="https://www.parkmycloud.com/blog/google-cloud-committed-use/?utm_medium=referral&amp;utm_source=medium&amp;utm_campaign=medium%20blogs&amp;utm_content=google-cloud-committed-use">3-year committed use discount</a>.</p><p>Google does not charge you for instances if they are preempted in the first minute after they start running.</p><p><strong>Note:</strong> Google Cloud <a href="https://www.parkmycloud.com/blog/google-cloud-credits/?utm_medium=referral&amp;utm_source=medium&amp;utm_campaign=medium%20blogs&amp;utm_content=google-cloud-credits">Free Tier credits</a> for Compute Engine do <em>not</em> apply to preemptible instances.</p><h3>How a preemptible VM differs from a regular one ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*AvTRvsg6zBcwfCn6i3GocA.png" /><figcaption>Comparison between preemptible VM / Standard instances</figcaption></figure><p>Azure also have &quot;similar&quot; offers: <a href="https://docs.microsoft.com/en-us/azure/batch/batch-low-pri-vms">Low priority VM&#39;s</a> and <a href="https://docs.microsoft.com/en-us/azure/virtual-machines/spot-vms">Spot instances</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*tc1-536ZRybrlEchldckyg.png" /><figcaption>Low priority and spot instances offer in Azure</figcaption></figure><h3>What issues do Spot VMs have?</h3><p>Obviously the biggest concern with Spot instances is that you may not be able to get resource. This is not an issue with the service, it is how it is designed to work, by you need to be aware of this and make sure you are happy with that approach.</p><p>Beyond that, there are a few limitations in the service that I think you should be aware of:</p><ul><li>B series VMs are not supported</li><li>Promo Sizes are not supported</li><li>Spot VMs cannot use ephemeral disks</li><li>Azure China is not supported</li><li>Spot VMs are not available on Benefit, Sponsored or Free subscriptions</li><li>You cannot convert a spot VM to a regular VM or regular to spot, you would have to delete the VM and attach the disk to a new VM</li><li>Machines which are evicted and de-allocated are not turned back on when capacity or price comes back inside allowed limits, you need to manually turn them back on</li><li>You will be unable to create your VM if capacity or pricing are not inside allowed limits</li></ul><p>And of course AWS also has your kind of <em>on budget </em>VM&#39;s: <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html">AWS Spot Instances</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*cjlbpt50aKX7zd6tW7Djtw.png" /><figcaption>Comparison between GCP preemptible instances and AWS spot instances</figcaption></figure><p>Long story short: You will effectively pay less using this kind of instances, but you should not rely 100% on it if you&#39;re running a production environment.</p><p>Lets say it again: <strong>You should not rely 100% on it if you’re running a production environment.</strong></p><h3>How use preemptible VM sets in a production environment (example approaches)</h3><p>So, you read my warning and still want to save some money having preemptible VM&#39;s in a production environment huh? OK, I can understand the &quot;FinOps&quot; approach on it (and how good you will look to management saying &quot;we have more resources and are SAVING MONEY! — Hope it led you to have a salary raise and not just a &quot;good job&quot; from your boss, lol).</p><p>OK, lets cut off the b******t: How we can do it ? Please remember it just a example and should be adjusted to your real needs.</p><p><strong><em>Scenario 1:</em></strong> Multi-zone cluster, main node pool with 1 VM per zone, autoscale node pool with <strong><em>n </em></strong>VM&#39;s, preemptible nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*U9Dea2sQzn49a4MBq9035g.png" /><figcaption>Scenario 1: Example strategy for deploy preemptible VM&#39;s in a k8s cluster</figcaption></figure><p>So, what we have here in detail:</p><ul><li>Cluster its inside the <strong>europe-west1 region.</strong></li><li>Inside <strong>europe-west1</strong> region we&#39;re deploying the cluster in <strong>a</strong>, <strong>b</strong> and <strong>c zones.</strong></li><li>Inside the <strong>a</strong>, <strong>b</strong> and <strong>c zones</strong> we have a <em>main </em>node pool, with 1 regular VM in which zone — Those VM&#39;s its here with the intent of <em>&quot;hold the fort&quot;</em> if Google need <strong>ALL</strong> resources in the region and kill all our preemptible VM&#39;s.</li><li>Also inside the <strong>a</strong>, <strong>b</strong> and <strong>c zones</strong> we have a second node pool (with autoscaling enabled), with <em>n </em>preemptible VM&#39;s, and those which will have the main role of have our k8s resources up and running.</li></ul><p><strong><em>Scenario 2:</em></strong> Single-zone cluster, main node pool with 0 VM&#39;s and autoscale enabled, second node pool with (optional) autoscale, with <strong><em>n </em></strong>VM’s, preemptible node (Thanks again for this one <a href="https://github.com/psychopenguin">Fábio</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*SHlE0BOnefGyAY_QgarLNQ.png" /><figcaption>Scenario 2: Example strategy for deploy preemptible VM’s in a k8s cluster</figcaption></figure><p>So, what we have here in detail:</p><ul><li>Cluster its inside the <strong>europe-west1 region.</strong></li><li>Inside <strong>europe-west1</strong> region we’re deploying the cluster only in <strong>a zone.</strong></li><li>Inside the <strong>a zone </strong>we have a <em>main </em>node pool, with 0 regular VM started by default — But this node pool have autoscale enabled (more of why 0 nodes are here by default follows).</li><li>Also inside the <strong>a zone</strong> we have a second node pool (with optionally enabled autoscaling), with <em>n </em>preemptible VM’s, and those which will have the main role of have our k8s resources up and running.</li><li>What happens in this case is: When doing the deployments, you can set the preferred node pool to be the preemptible one, and if don&#39;t exist in that pool any node available to schedule this workload, Kubernetes will fallback to main node pool (which one has autoscaling enabled but starts with 0 nodes), and will spin up a node to run your workload. The point here is adjust accordingly the number of nodes you will need in second node pool (or let autoscale enabled in it), in order to prevent a big bill at the end of the month because of a huge usage of the first node pool.</li></ul><p>You can schedule a workload on a preemptible node pool and manage it with Kubernetes deployment configurations.</p><p>Then, to control pod scheduling, we use the Kubernetes node affinity feature, which gives us hard and soft preferences for scheduling pods. We use hard preferences to ensure that a particular pod won’t ever be scheduled on a preemptible node. Simply add the following lines to your pod or deployment spec:</p><pre>affinity:<br>  nodeAffinity:<br>    requiredDuringSchedulingIgnoredDuringExecution:<br>      nodeSelectorTerms:<br>      - matchExpressions:<br>        - key: cloud.google.com/gke-preemptible<br>          operator: DoesNotExist</pre><p>Soft preferences, by contrast, just give Kubernetes your scheduling preferences.</p><p>Here’s an example of how to modify your pod or deployment spec with <em>PreferredDuringSchedulingIgnoreDuringExecution</em> to tell Kubernetes to run workload on a preemptible node pool if preemptible VMs are available:</p><pre>...<br>spec: <br>  affinity:<br>    nodeAffinity:<br>      preferredDuringSchedulingIgnoredDuringExecution:<br>      - preference:<br>          matchExpressions:<br>          - key: cloud.google.com/gke-preemptible<br>            operator: Exists<br>        weight: 100<br>...</pre><h3>Additional steps — Tuning</h3><p>Of course, with the scenario presented above, you infrastructure are ready to be deployed and have your workload running on top of it, and now we need to optimize it and ensure we don&#39;t have any surprises during the long run, so that is a checklist of items we have in place to ensure everything runs smoothly:</p><ol><li>Set autoscale to preemptible node pool, and remember the <strong>minimum VM count</strong> will be set multiplying by 3 (since we have 3 zones in place in our cluster), so adjust the minimum VM count to hold accordingly to the normal load of your environment.</li><li>Use a tool to kill the &quot;old&quot; preemptible VM&#39;s in a controlled way, my good friend (and my GNU/Linux, DevOps and Mario Odyssey mentor) <a href="https://github.com/psychopenguin">Fábio</a> wrote a <a href="https://github.com/psychopenguin/noderecycler">noderecycler</a> to do exactly that.</li><li>Set <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/">podAntiAffinity and/or podAffinity rules </a>in your deployments, to ensure the replicas of your deployments don&#39;t be hosted at same node (and the service don&#39;t goes down if the node got removed by achieve the threshold defined age in kill tool set at previous step).</li><li>Remember if you use PVC&#39;s in our deployment, it got attached to the node (or set of nodes) and those are <strong>not </strong>shared between zones. An alternative should be the usage of <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/persistent-volumes#regional_persistent_disks">regional persistent disks</a>, its (a bit) more expensive, but solves the issue of having a PVC attached to a single zone.</li><li>If you have specific deployments which <strong>can&#39;t </strong>be killed (because just can have 1 replica running, or its a super-specific application or even because its a, don&#39;t know, a database maybe?), set a <a href="https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/">nodeAffinity rule</a>, to ensure this deployment will run only in the main node pool (which one has regular VM&#39;s — and not got killed every day).</li><li>Use some kind of analysis tool to identify your cloud costs and the best strategy to follow (My good friend <a href="https://medium.com/u/c5ed2b8d1805">Gustavo Mota</a> pointed me to <a href="https://spot.io/products/cloud-analyzer/">cloud-analyzer</a> — Previously known as spotinst)</li></ol><h3>A word of caution</h3><p><a href="https://github.com/psychopenguin">Fábio</a> also referred to me a possible problem you should have if going to have this approach: Inter-zone traffic costs, which (depending of how your application is set and how much traffic it generate between services) could transform your monthly bill in a HUGE one!</p><p>According to <a href="https://cloud.google.com/run/pricing#pricing_table">Cloud Run Pricing page of Google</a> we have the following costs related to egress traffic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*rwOeN2V3KUsE8CTWcJQPuA.png" /><figcaption>Egress traffic detail — Google Run Pricing page detail</figcaption></figure><p>If your cluster already have an multi-region deployment, its kinda nothing to worry about (because you already know how much this traffic represent in your monthly bill). But even in this case you can implement some strategies to keep cost down, like:</p><ul><li>Utilize a service mesh</li><li>Keep the services who need to exchange huge amount of traffic together in same region (and/or) nodes using affinity rules</li></ul><h3>Conclusion</h3><p>Of course that its not an exhaustive list of strategies to make you save money using preemptible instances, but to <em>open your horizons </em>about it and let you explore the best approach to your environment.</p><p>If you have something which can be used to expand this article, please <a href="https://about.me/andersonsleite">let me know</a>.</p><p>That&#39;s all for today, stay safe!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91e379bf2c3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>