IaC tools vary in the details of how they work, but they all take one of two approaches to infrastructure automation — declarative or imperative. It’s important to understand the differences between these two programming language styles when selecting an IaC tool.
With the declarative approach, the user “declares” what the provisioned infrastructure should look like by specifying a list of resources and required properties. Then the IaC tool installs and configures all the infrastructure components and manages code versioning. With the imperative approach, users specify a list of commands they want the IaC to run so the infrastructure will be provisioned step by step. Put simply, declarative programming lets users say what infrastructure resources they want, and imperative programming lets them say how they want the infrastructure resources created.
Although both approaches can be used to create the desired infrastructure, there are some differences to consider. To understand them clearly, let’s discuss how each approach handles instructions illustrated by the example of taking a taxi to the airport. A declarative instruction would be to tell the driver, “Get me to the airport by 11 a.m.” Here, you’ve stated your desired outcome, and it’s up to the taxi driver to determine the best route, speed and other factors to get you there on time.
An imperative approach, on the other hand, would be to give the driver explicit instructions on how to get you to the airport by 11 a.m. For example, “Pick me up at 10:15 a.m., take a left at the corner, get on the freeway and accelerate to 65 mph … ” Both of these approaches will get you where you need to go, but the second approach doesn’t leave much wiggle room if the driver encounters an unexpected obstacle, like a road detour or a car accident on the freeway. Declarative and imperative instruction work much the same way in IaC.
Declarative tools handle all the complexities of provisioning your desired infrastructure. However, you’ll have little insight into why it made the choices it did without consulting the tool’s administrator. An imperative approach gives you more control over how your infrastructure is provisioned, but it requires more work from the developer, and its reliance on explicitness means if it encounters an obstacle at any step, you’ll have to stop and work out the solution — which can make this approach tough to manage at scale. The “best” style depends on several factors, such as how much code you’re writing, the likelihood you’ll be updating the infrastructure down the road, and how much control you require over the way changes are made to your cloud services.