Author: Ganesh Datta

  • Best of 2022: How DORA Metrics Can Measure and Improve Performance

    Best of 2022: How DORA Metrics Can Measure and Improve Performance

    As we close out 2022, we at devopsy.kinsta.cloud wanted to highlight the most popular articles of the year. Following is the latest in our series of the Best of 2022.

    A technology company’s most valuable assets are its people and data, especially data about the organization itself. By knowing what data to track over time, engineering leaders can measure how efficiently their DevOps teams are operating and enable them to maximize their value stream to deliver the best possible product to end users.

    After years of research, Google’s DevOps Research and Assessment (DORA) team identified four key metrics for evaluating a team’s performance:

    1. Lead time for changes
    2. Deployment frequency
    3. Mean time to recovery
    4. Change failure rate

    DORA metrics have now become the standard for gauging the efficacy of software development teams and can provide crucial insights into areas for growth. These metrics are essential for organizations looking to modernize and those looking to gain an edge against competitors. Below, we’ll dive into each metric and discuss what they can reveal about development teams.

    Lead Time for Changes

    Lead time for changes (LTC) is the time between a commit and production. LTC indicates how agile a team is—it not only tells you how long it takes to implement changes but how responsive the team is to the ever-evolving demands and needs of users. The DORA team identified these benchmarks for performance in their Accelerate State of DevOps 2021 report:

    Elite performers: Less than one hour

    High performers: One day to one week

    Medium performers: One month to six months

    Low performers: More than six months

    LTC can reveal symptoms of poor DevOps practices: If it takes teams weeks or months to release code into production, there are inefficiencies in their process. One can minimize their LTC through continuous integration and continuous delivery (CI/CD). Encourage testers and developers to work closely together so everyone has a comprehensive understanding of the software. Consider building automated tests to save more time and improve the CI/CD pipeline.

    Because there are several phases between the initiation and deployment of a change, it’s wise to define each step of the process and track how long each takes. Examine the cycle time for a thorough picture of how the team functions and further insight into where they can save time.

    One should be careful not to let the quality of their software delivery suffer in a quest for faster changes. While a low LTC may indicate that a team is efficient, if they can’t support the changes they’re implementing or they’re moving at an unsustainable pace, they risk sacrificing the user experience. Rather than compare the team’s Lead Time for Changes to other teams’ or organizations’ LTC, one should evaluate this metric over time and consider it an indication of growth (or stagnancy).

    Deployment Frequency

    Deployment frequency (DF) is how often you ship changes; how consistent your software delivery is. This metric is beneficial when determining whether a team is meeting goals for continuous delivery. According to the DORA team, these are the benchmarks for Deployment Frequency:

    Elite performers: Multiple times a day

    High performers: Once a week to once a month

    Medium performers: Once a month to once every six months

    Low performers: Less than once every six months

    The best way to enhance DF is to ship a bunch of small changes, which has a few upsides. If deployment frequency is high, it might reveal bottlenecks in the development process or indicate that projects are too complex. Shipping often means the team is constantly perfecting their service and, if there is a problem with the code, it’s easier to find and remedy the issue.

    If a team is large, this may not be a feasible option. Instead, one may consider building release trains and shipping at regular intervals. This approach will allow the team to deploy more often without overwhelming your team members.

    Mean Time to Recovery

    Mean time to recovery (MTTR) is the average amount of time it takes your team to restore service when there’s a disruption like an outage. This metric offers a look into the stability of your software, as well as the agility of your team in the face of a challenge. These are the benchmarks identified in the State of DevOps report:

    Elite performers: Less than one hour

    High performers: Less than one day

    Medium performers: One day to one week

    Low performers: Over six months

    To minimize the impact of degraded service on your value stream, there should be as little downtime as possible. If it’s taking your team more than a day to restore services, you should consider utilizing feature flags so you can quickly disable a change without causing too much disruption. If you ship in small batches, it should also be easier to discover and resolve problems.

    Although mean time to discover (MTTD) is different from mean time to recovery, the amount of time it takes your team to detect an issue will impact your MTTR—the faster your team can spot an issue, the more quickly service can be restored.

    As with lead time for changes, you don’t want to implement sudden changes at the expense of a quality solution. Rather than deploy a quick fix, make sure that the change you’re shipping is durable and comprehensive. You should track MTTR over time to see how your team is improving and aim for steady, stable growth.

    Change Failure Rate

    Change failure rate (CFR) is the percentage of releases that result in downtime, degraded service or rollbacks, which can tell you how effective a team is at implementing changes. As you can see, there is not much distinction between performance benchmarks for CFR:

    Elite performers: 0-15%

    High, medium and low Performers: 16-30%

    Change Failure Rate is a particularly valuable metric because it can prevent a team from being misled by the total number of failures they encounter. Teams who aren’t implementing many changes will see fewer failures, but that doesn’t necessarily mean they’re more successful with the changes they do deploy. Those following CI/CD practices may see a higher number of failures, but if CFR is low, these teams will have an edge because of the speed of their deployments and their overall success rate.

    This rate can also have significant implications for the value stream: It can indicate how much time is spent remedying problems instead of developing new projects. Because high, medium and low performers all fall within the same range, it’s best to set goals based on the team and the particular business rather than compare to other organizations.

    Putting it All Together With DORA Metrics

    As with any data, DORA metrics need context, and one should consider the story that all four of these metrics tell together. Lead time for changes and deployment frequency provide insight into the velocity of a team and how quickly they respond to the ever-changing needs of users. On the other hand, mean time to recovery and change failure rate indicate the stability of a service and how responsive the team is to service outages or failures.

    By comparing all four key metrics, one can evaluate how well their organization balances speed and stability. If the LTC is within a week with weekly deployments but the change failure rate is high, then teams may be rushing out changes before they’re ready, or they may not be able to support the changes they’re deploying. If they are deploying once a month, on the other hand, and their MTTR and CFR are high, then the team may be spending more time correcting code than improving the product.

    Because DORA metrics provide a high-level view of a team’s performance, they can be beneficial for organizations trying to modernize—DORA metrics can help identify exactly where and how to improve. Over time, teams can measure where they have grown and which areas have stagnated.

    Those who fall into the elite categories can leverage DORA metrics to continue improving services and gain an edge over competitors. As the State of DevOps report reveals, the group of elite performers is rapidly growing (from 7% in 2018 to 26% in 2021), so DORA metrics can provide valuable insights for this group.

    But remember that data will only get you so far. To get the most out of DORA metrics, engineering leads must know their organization and teams and harness that knowledge to guide their goals and determine how to effectively invest their resources.

  • A Guide to Cloud Migration Trends and Strategies

    A Guide to Cloud Migration Trends and Strategies

    For several years, we have witnessed widescale cloud adoption as a software infrastructure growth and maintenance strategy. Spending on cloud application services (SaaS) continues to grow as monolithic applications are replaced by microservices-based apps and monoliths become relics of the past. In 2021 alone, companies spent $410.9 billion on public cloud services, and Gartner expects this number to rise by 20.4% in 2022 to reach $494.7 billion. But as this movement continues to evolve, engineering leaders preparing their cloud migration strategy must be up to speed on the latest key trends.

    Is Migrating to the Cloud Cost-Effective?

    For companies migrating to the cloud now, the process is no longer a simple transition from on-premises to remotely hosted servers. Cloud service providers now offer a wide variety of options, and companies run the risk of overspending in the cloud marketplace.

    A lack of clarity of their business and product needs or submission to shiny object syndrome can drive companies to spend on non-essential services, especially during migration. It is easy to fall into this trap; companies only realize it after they have committed and try to undo the damage by reversing the process.

    Although many public cloud providers offer pay-as-you-go pricing, companies often purchase more services than they use. When companies are unclear about their objectives, such expenditure is more extravagant than the utility. This awareness of cloud spending has encouraged companies to take stock of their needs and expenses, and when they do not add up, to consider partly shifting back to on-premises.

    But Isn’t On-Premises a Thing of the Past?

    Not yet, but gone are the days of mindlessly unloading entire infrastructures into the cloud. Increasingly, companies are aware of the costs of pulling their data from the cloud.

    For many, security and control concerns motivate them to keep data on-premises. The public cloud has its benefits, but private storage has its place, too, especially for some components of your software. All in all, on-premises is here to stay, as companies continue to acknowledge and appreciate its value despite their reliance on public cloud environments.

    Why Do Companies Choose Cloud Migration in 2022?

    Cloud technologies can potentially deliver faster and better-performing experiences to end users, while innovations are giving rise to new services that cloud vendors can capitalize on. Various use cases are surfacing as companies understand the cloud better and see its potential. They are pushing the boundaries on how they can use the cloud, and cloud service providers are keeping track of the changing nature of the demand.

    For example, cloud-based gaming platforms like Amazon Luna are seeing significant growth. The cloud is also of great value to artificial intelligence and machine learning efforts, and these are often intertwined.

    The Great Resignation phenomenon also drives some companies towards the cloud. Although some knowledge is needed when moving to the cloud, cloud services offer automation and require less employee supervision in the long term.

    The COVID-19 pandemic has also been a catalyst for accelerating cloud adoption, making resiliency a priority. Companies can stay afloat in an emergency if their workloads are moved to the cloud. It comes at a cost, sure, but allows companies to outsource time-consuming responsibilities and focus resources elsewhere. While this was most significant in 2020 and 2021, this logic remains relevant.

    Cloud computing is also helping companies improve performance, efficiency and scalability. In addition to AI, the cloud will be instrumental in the development of more powerful augmented and virtual reality apps.

    Approaches Defining Cloud Migration Today

    The possibility of these approaches or facilities also motivates companies to migrate to the cloud:

    Containerization: The process of compiling and storing a service, along with its dependencies, in a container. Due to their small size, multiple containerized applications can run on a server, allowing for easier and cheaper shipping of the service. According to CNCF’s 2021 Annual Survey, containerization is now a mainstream practice, and Kubernetes, for instance, is a heavyweight in this domain, with 96% of companies employing or evaluating it.

    Security: In Q1 of 2022 alone, 90% of data breaches had their origins in cyberattacks. Mindful of this alarming trend, companies are factoring security concerns into their cloud adoption strategies. We are also witnessing a shift in businesses’ approach to security via DevSecOps: Incorporating security as a continuous practice from the beginning of the software development life cycle instead of relegating it to the back-burner until the last moment. Additionally, frameworks like secure access service edge (SASE) and customized cloud disaster recovery strategies are becoming essential elements of cloud adoption.

    Sustainability: Sustainability is becoming a key component in most business models. Companies are eager to adopt practices and models that reduce their carbon footprint. This impetus is also emerging from business partners and investors who are beginning to employ sustainability as a critical factor when deciding which companies to work with. When a cloud migration is planned carefully, chances are that you will retire certain services in your infrastructure and make decisions about what to migrate and what to retain. By optimizing your migration strategy, you are likely to only run and pay for the services you need, ensuring that your energy expenditure is under control.

    Edge computing: Edge computing, a $176 billion market in 2022, emphasizes the importance of building data centers locally; i.e., closer to where they are needed for storage and computational purposes. It solves any bandwidth and latency issues. Improved security is another added benefit of this practice. Edge computing has a bright future as it attempts to compensate for some of the pitfalls of using centralized servers in the cloud.

    Cloud-native applications: Cloud-native applications are easier to work with on the cloud, as they are designed and built on the cloud itself, not rearchitected to ensure compatibility with cloud services. When compatibility is not a concern, they can leverage various benefits offered by cloud services. As a result, scalability, flexibility and resilience are built into these applications. With cloud adoption, companies are increasingly in favor of cloud-native applications. This subsequently informs their migration strategy as they decide which services to retire, rearchitect or build anew once the actual migration is complete.

    How Does the Hybrid Cloud Fit In?

    Hybrid computing is on the rise as it leverages the public and the private cloud to deliver maximum benefit to companies with little to no compromise. The public cloud offers scalability, flexibility and speed, while the private cloud provides cost-effectiveness, security and compliance with regulations. While sensitive data can rest on the private cloud, frequently accessed data can be stored in public servers like AWS and Google Cloud. Investing in a hybrid cloud strategy from the point of migration itself can go a long way in giving companies access to the best of both worlds.

    Similar to a hybrid cloud environment, a multi-cloud strategy where companies distribute workloads across multiple clouds put some control into the company’s hands and ensures additional flexibility. By working across cloud services, companies can pick and choose which services are most compatible with their application’s components. These can include services offered by different cloud providers.

    Cloud Providers Seeing Growth, and What They are Doing Differently

    Serverless cloud environments: Cloud vendors like Amazon, Microsoft and IBM are pushing serverless cloud services. Although these continue to rely on servers (despite the name), companies don’t rent servers or pay fixed charges. Instead, the storage and bandwidth infrastructure scales with the software as and when it requires it. Companies do not need to concern themselves with technicalities and can focus on innovation and improving their existing applications. An added advantage is the provision of safe testing environments that encourage developers to tinker with cloud services and develop solutions for potential failures or outages. Serverless cloud solutions are also beneficial for smaller companies that need not invest large amounts of capital to ensure growth.

    Partnerships: To meet the soaring demand for cloud services, partnerships among cloud providers are also on the rise. By partnering with other service providers, companies can offer more services by leveraging the resources and reputations of one another while strengthening their competitive edge in the cloud market.

    Industry optimization: Cloud adoption is not limited to software companies. Businesses across industries like healthcare, finance and retail are migrating their infrastructures to the cloud. This variety in demand has encouraged providers to customize their services to meet the specific requirements of each industry. Often, these include regulatory compliance needs in these sectors.

    The cloud is only getting bigger and better. You can develop a well-curated transition strategy with the knowledge of current cloud migration trends. Additionally, identifying your requirements at an early stage will go a long way in leveraging the cloud to your advantage.

  • 5 Testing Strategies For Deploying Microservices

    5 Testing Strategies For Deploying Microservices

    With rigorous development and pre-production testing, your microservices will perform as they should. However, microservices need to be continuously tested against actual end-user activity to adapt the application to changing preferences and requests. This article will cover five deployment strategies that will help developers and DevOps teams when releasing new features or making changes to microservices-based applications.

    Always Test in Production

    A staging environment is a necessary but insufficient step toward building a robust microservices infrastructure. Although indicative, it is not a substitute for evolving user traffic and behavior. When real users interact with the software during production, the services may not perform as efficiently.

    Users are unpredictable. They may make requests you have not accounted for when drawing up communication paths. Or your microservices architecture may not sustain the actual production traffic. When testing with real end-users, you are sure of your software’s performance and can improve it or add new functionality. 

    The disadvantage of working with real users is that they will be impacted by any errors. However, with specific deployment strategies, you can identify the issues and minimize their impact on those users. 

    Depending on your goals, you can implement the following testing strategies in the deployment stage. They can be performed individually or in various combinations, as each approach varies in its contribution to deployment.

    Blue-Green Deployment

    A blue-green deployment uses two distinct yet identical production environments. For example, you deploy an inactive version of your application in the blue environment. At the same time, the latest version available to end users runs in the green environment. Next, you push code to add new functionality to the blue environment. 

    At this stage, you test the services in the blue environment to ensure that they are running smoothly. You can automate this process by using basic smoke tests. When the microservices pass these tests, you can instruct the load balancer to gradually redirect user traffic to this new environment.

    If the new functionality poses no problems, the router moves all traffic from the green to blue environment, but can immediately revert traffic in case of any errors. 

    Due to the identical nature of both environments and their reliance on each other, there is little to no downtime. The end user’s experience is largely unaffected and the developers can move quickly to fix any bugs.

    The old environment serves as a backup, making it possible to execute a rollback without any downtime. After releasing the latest version, you can decide to kill the old instances, but only after you are confident that the new environment will continue running without errors. You can also clone both blue and green environments to repeat the process with other feature deployments in the future.

    Canary Deployment

    Canary deployment is similar to blue-green testing in that it protects against release-related risks.

    The phrase “canary deployment” originates from an old mining practice of placing caged birds in mine shafts to detect the presence of harmful gases. If present, the gases would kill the canary before affecting the miners, thus providing an early warning to vacate the mine immediately.

    A canary deployment works on a similar principle. Instead of creating two separate environments, a canary deployment operates within the same microservice or infrastructure. The developers roll out a new service or application version with changes only to a fraction of the end-users.

    You can quickly detect errors or vulnerabilities while using the new service. The impact is temporary and minimal as the experiment is only run on a subset of users with most remaining unaffected. Once they are working and have passed verification, you can scale up the changes. 

    The biggest challenge for those running canary deployments is the requirement to run multiple versions of the same microservices so that they can be deployed to a few users at a time. Implementing multiple versions also means you need to keep track of which users are on which versions to run accurate business metrics and analytics. Such monitoring can get increasingly complex with multiple canary deployments within the same application.

    Feature Flags

    A feature flag or feature toggle is a change or feature written inside conditional code. Developers can turn the feature on or off depending on their testing requirements while the application is running and in use.

    The code is already deployed and there are two code paths: One with the code that implements the feature and one without it. The developer only needs to choose one of the two paths. When the switch is toggled on, the code chunk is executed as part of the flow. When switched off, that code is skipped and the feature is not implemented. The rest of the source code continues to run as usual, independent of the feature flag’s condition, with no disturbances in the end user’s experience.

    Once integrated, a feature flag allows you to turn on a feature for a select group of users. Unlike a canary deployment where the selection is random, feature toggles are usually employed in specific cases. For example, developers do not create two separate applications to implement free and paid subscription tiers. Instead, operating a feature flag allows you to make a particular feature accessible only to subscription users.

    Feature flags are especially attractive during testing as developers can use them to run small experiments throughout the application without relinquishing control. Being able to flip the switch remotely also makes rollbacks easier. The risk is negligible as the application is self-sufficient in that it can continue to run without the feature. 

    Feature flags generate complex user-to-service paths by way of permutations and combinations. For a specific user, it is difficult to determine the exact route they took when using the services. Feature flags complicate this by allowing each user to have a different experience, ultimately making the application hard to debug. These toggles are easy to get started with minimal risks, but their maintenance can quickly become complex. It is best to use them only when needed and with other deployment strategies.

    Traffic Shadowing

    With traffic shadowing or mirroring, the router duplicates incoming traffic to an already-released service and gives the copy to another service. The request and response mechanism between the user and the existing service remains intact. On the other hand, the second service with a copy of the traffic contains new features that require testing. Consequently, it does not interfere with the existing process. Instead, the copy is used to test its functionality.

    Its most significant benefit is that it allows the new version to receive the same traffic that is currently being received by the service it seeks to replace. There is no need to create test data or worry about replicating scale. This accuracy comes with little risk, as there is no tangible impact on the existing services. Developers can run all relevant tests on this production environment, such as testing for errors and performance metrics. The new version’s responses, which are not sent to users, can also be compared to those of the production service. Both versions operate independently of each other with different end goals. This can happen in real-time or a copy can be saved and replayed for future testing.

    Traffic shadowing can be used with other deployment techniques like blue-green or canary deployments. After successfully shadowing a production environment, the changes can be rolled out gradually using a canary deployment to gain maximum confidence before a full release.

    Shadowing can have unintended consequences, though, so you should exercise caution when deploying this strategy with services that have third-party dependencies. 

    A/B Testing

    Unlike blue-green and canary deployments, A/B testing is focused on user perception and experience of new features. It measures if and how end users are interacting with these features, whether they are easy to notice and use and gauges the application’s overall functionality. It provides developer teams with business-level insight to improve their application as the features are ultimately implemented using code.

    A/B testing divides users into groups that access different features. Group A, for example, sees a different user interface than group B, although members in both groups are making the same requests to access the application. Traffic is routed to separate builds or different configurations on a common build. This is done by considering aspects like the users’ operating systems and user agents. It must be run on a sample that is representative of your end users. The test also needs to display statistically significant results to be valid.

    This test can be combined with blue-green or canary deployments as they handle the actual feature deployments that this strategy tests. After comparing the versions shown to the groups, the one that has performed better can be pushed to release for all users. 

    Building your Deployment Strategy

    Each strategy outlined can be used independently or together in a combination that best suits your goals, workflow and microservices requirements. They allow you to identify and reduce the impact of any vulnerabilities that may only surface at the final stage of your software’s release. Implementing them can be a somewhat complex process, especially with larger architectures and dependencies. But by implementing any of these strategies, your team will release the best possible version of your application. 

  • Why MTTR is a Vital Metric for DevOps Teams

    Why MTTR is a Vital Metric for DevOps Teams

    In DevOps, every second counts. System failures mean your engineers lose valuable time improving software and developing new features. So how do you effectively detect and manage these issues? Mean-time-to-resolve (MTTR) can provide insight into how effectively your DevOps team responds to incidents and how reliable your software is. It’s difficult to know how your team can improve or determine a performance baseline if you don’t have data to analyze your incident management workflows. In this article, you will learn about this valuable metric, interpret it and leverage this information to minimize downtime.

    Why MTTR Matters

    Whether you’re a legacy organization striving to modernize, a startup looking to gain an edge or somewhere in between, MTTR is a vital metric for your organization. It can indicate whether your processes are standardized and can highlight crucial areas for optimization. Most importantly, mean-time-to-resolve provides insight into how stable your software is and how responsive your team is over time.

    Mean-Time-to-Resolve and How to Interpret it

    MTTR can stand for many different things: Mean-time-to-repair, mean-time-to-recovery, mean-time-to-restore or mean-time-to-resolution are just a few interpretations of this versatile acronym. Each of these metrics examines a different aspect of addressing an incident. For example, mean-time-to-repair is the average time it takes engineers to fix a problem, calculated from the moment they begin to the moment a change is pushed to production. But this metric does not account for the amount of time between when an alert comes in and when work begins.

    Mean-time-to-resolution is the most high-level of these metrics—it considers the average time from when an alert comes in until the incident has been resolved, including postmortems and implementing process changes to avoid the same issue in the future. While the standards for this metric can vary by industry, the highest-performing DevOps teams see an MTTR of less than one day.

    Because it is such a comprehensive metric, a high mean-time-to-resolve measurement might indicate problems with alerting or that your engineers are spending a lot of time on repairs. Therefore, it’s essential to look at MTTR over time and analyze each component of your incident management workflow: Time to alert engineers, diagnose the issue, test fixes, ship to production, conduct reviews and learn from the incident.

    It may also be helpful to examine mean-time-to-resolve in conjunction with other metrics. To determine if your DevOps team is facing production challenges, evaluate your change failure rate (CFR) to see how many releases result in a downgraded service. Other DORA metrics, like deployment frequency and lead-time-to-changes, are perfect companions for mean-time-to-resolve.

    To establish the reliability of your software, you can look at mean-time-to-resolve beside mean-time-between-failures (MTBF), which calculates the average amount of time between incidents. If you’re updating your software often, compare mean-time-to-resolve with mean-time-to-failure (MTTF), which measures its duration before a program needs to be redesigned for functionality. To gain insight into your alerting processes, examine mean-time-to-detect (MTTD), which evaluates the time it takes your team to recognize that an issue exists.

    How to Improve Mean-Time-to-Resolve

    Alerting is the first stage of responding to an incident and should be one of the first areas to target when working to reduce mean-time-to-resolve. Ensure alerts are actionable and that DevOps team members have the tools they need to respond immediately. A straightforward escalation process is essential: Define responsibilities for each member and train the team in one another’s roles so that the process never grinds to a halt if someone is unavailable.

    Preemptive monitoring can help you get ahead of problems before they arise—by proactively checking for potential incidents, you can avoid unexpected downtime.

    The best way to improve MTTR is to standardize your operating procedures with runbooks. Without runbooks, DevOps teams have to respond without a clear direction and spend time messaging one another for information—they can’t act immediately. With runbooks, however, your organization’s knowledge base is centralized and accessible to all team members, enabling them to respond as soon as an issue comes up.

    If you’re already using runbooks, consider automating responses. Automation not only improves your mean-time-to-resolve but will give your DevOps team more time to devote to implementing long-term changes that improve the stability of your service.

    When implemented correctly, mean-time-to-resolve is a proven metric that can indicate how effective your DevOps team responds to challenges and how reliable your software is. But be careful not to incentivize the wrong behavior in a quest to minimize this metric. You could, for example, quickly reduce MTTR by eliminating all alerting protocols, but that would also mean poor service for your end users and likely result in poor team morale. Examine this metric over time and aim for slow and steady growth rather than a quick fix.

  • Everything You Need to Know About Cookiecutter

    Everything You Need to Know About Cookiecutter

    Cookiecutter is a templating library for creating project boilerplates in any programming language. When individuals, teams and organizations create projects, they must follow consistent standards so that those projects are easily readable and searchable. Templates accelerate the code writing process, too, since developers are able to spend less time on setup and can get straight to the actual implementation. 

    Cookiecutter is a Python package, easily installable with pip or other package managers. It enables you to create and use templates for microservices and other software projects. It is a command line tool that doesn’t require knowledge of Python to use. Cookiecutter is widely used among software engineers, researchers, data scientists and other technical roles.

    Creating a template is simple and requires updating a cookiecutter.json file. Using a template requires running the cookiecutter command with the appropriate directory to create a new project.

    Here’s an example template for a Python package that the Cookiecutter team maintains. To use the template, install Cookiecutter first and then run the following command in your terminal:

    Cookiecutter https://github.com/audreyfeldroy/cookiecutter-pypackage.git 

    Go through the series of prompts and voila! In just a few moments, you have the skeleton of a completely functional Python package. Swap out the template for something else and you could just as easily spin up a mobile app, a data science notebook, or any other project on your favorite cloud service. There’s an entire community with thousands of templates to choose from.

    Creating custom templates to fit your and your organization’s needs is also simple and powerful. We’ll cover how to do that below.

    Who is Cookiecutter For?

    Cookiecutter is for individuals, teams and companies to standardize their project development process and accelerate new project creation.

    Example use cases include:

    • Learning a new framework: Cookiecutter lowers the barriers to entry for developers unfamiliar with a particular framework. You can find an expert’s template for a framework you’re learning and quickly get started with a configuration that is known to work.
    • Onboarding: Standardization makes collaboration much more manageable. New team members can immediately follow best practices without the risks of copying, pasting and trying to edit just the correct variables.
    • Enforcing standards in an organization: Consistent foldering, file-naming conventions and other patterns enable large teams to maintain an organized codebase.

    Cookiecutter Features

    Templates

    The heart of a template is the cookiecutter.json file, which might look something like this:

    {

      “full_name”: “Alice Cookie”,

      “email”: “foobar@example.com”,

      “project_name”: “Django Boilerplate”,

      “version”: “0.1.0”

    }

    These key-value pairs determine the prompts a developer needs to answer when using a template. The command line interface iterates over the keys, prompting a developer to set the various parameters. If a developer does not specify something, Cookiecutter uses default values.

    A template needs to have files and directories worth copying and reusing, such as the skeleton code for a particular framework. Cookiecutter uses these inputs to modify the template. To connect this boilerplate to the inputs, Cookiecutter uses the Jinja2 templating language. With Jinja2, Cookiecutter identifies all instances of the text {{cookiecutter.variable_name}} and replaces that boilerplate with the actual value of the variable. This works both within files as well as for file and directory names.

    Loops and Conditional Logic

    Jinja2 is very powerful and can do much more than just text substitution. It comes with control structures including for loops and if statements. It even has macros that are analogous to functions in programming languages. Since all of Cookiecutter’s templating uses Jinja2, it can leverage the same control flow features. This opens up enormous possibilities. For example, you could prompt a developer to specify which device types for which they are building an app and have unique behaviors depending on the response.

    Hooks

    Pre/post-generate hooks let you run Python or shell scripts before and/or after generating a project. Inputs from the template prompts are fair game within hooks and work similarly to the way they would elsewhere in the project with Jinja2 syntax. This means you can run a script to validate a developer’s responses to the prompts. Other applications of hooks include cleaning up unwanted files or otherwise using logic that would be complicated by just using Jinja2.

    What Are the Limitations?

    By design, templates are prescriptive with regard to a project’s setup, presenting all kinds of advantages as discussed above. On the other hand, a template might be opinionated in a way that does not align with either an individual developer’s or an organization’s preferences. In that case, it may be worth choosing another template or revising an existing one. Forcing a template in a situation that doesn’t make sense is less-than-ideal.

    What Are Some Alternatives or Extensions?

    Boilerplate for Specific Frameworks

    While Cookiecutter is compatible with almost any framework, some frameworks do have custom boilerplate that is readily available. If you were to start a React app, for example, there is a great boilerplate available to use as a starting point, and other communities often maintain similar ways to get started. Boilerplate is not incompatible with Cookiecutter, and you’ll find templates from popular boilerplate that you can use, too.

    Cruft Keeps Templates Organized

    As with any new process, there is some overhead involved to stay organized with Cookiecutter. When a team starts to manage dozens of templates or more, it’s especially important to keep templates up-to-date. Cruft works alongside Cookiecutter to not only make projects but to update existing ones as a template evolves. Cruft also has template validation capabilities to ensure projects match the latest version of a template.

    Learn More About Cookiecutter

    The Cookiecutter community has lots of resources to help you dig deeper.