Sobes.tech
Junior

What is the declarative approach in DevOps?

sobes.tech AI

Answer from AI

The declarative approach in DevOps focuses on describing the desired end state of the system, rather than the sequence of steps to achieve it. Tools that use this approach are responsible for defining and executing the necessary operations to bring the system into this state.

Main differences from the imperative approach:

  • Imperative: Describes how to achieve the goal (sequence of commands).
  • Declarative: Describes what the final state should be.

Examples of tools using the declarative approach:

  • Kubernetes: Describes the desired number of pod replicas, service configuration, etc., in YAML files. Kubernetes maintains this state.
  • Terraform: Infrastructure as code. Describes the desired infrastructure (virtual machines, networks, load balancers) in .tf files. Terraform creates or modifies resources according to this description.
  • Ansible (partially, in playbooks): Tasks (tasks) often describe the end state (e.g., "ensure the package is installed", "ensure the file exists with specific content").

Advantages:

  • Idempotency: Applying the same declarative description multiple times will not cause unintended changes if the system is already in the desired state.
  • Resilience: Tools strive to restore the desired state in case of deviations.
  • Ease of understanding: State descriptions are often more intuitive than detailed execution scripts.
  • Improved scalability: Easier to manage large, complex systems by focusing on the end result.
  • Reduction of configuration drift: The system is actively maintained in the described state.

Example (comparing approaches):

Creating a file /etc/myapp.conf with content "data=value".

Imperative:

# Check if the file exists
if [ ! -f /etc/myapp.conf ]; then
  # Create directory if it doesn't exist
  mkdir -p /etc
  # Create the file
  echo "data=value" > /etc/myapp.conf
fi
# Or simply:
# echo "data=value" > /etc/myapp.conf

Declarative (principle, not actual syntax):

file: /etc/myapp.conf
state: present # The file should exist
content: "data=value" # With this content

An instrument using the declarative approach will determine whether it needs to create the file, change its content, or just ensure its existence.