Chef Loops

Chef is a powerful configuration management tool that turns infrastructure into code. With the help of Chef, Users can easily manage, configure and deploy the resources across the network from the central location of the environment (cloud, on-premises, or hybrid).

Using chef Loops

Loops are typically used to repeat a task using different input values. For instance, instead of creating 10 tasks for installing 10 different packages, we can create a single task and use a loop to repeat the task with all the different packages we want to install.

Chef supports all Ruby loop structures for creating loops inside recipes. For simple usage, each is a common choice

['vim', 'git', 'ntp'].each do |package|

 apt_package package do

   action :install

 end

end

Instead of using an inline array, we can also create a variable or attribute for defining the parameters you want to use inside the loop. This will keep things more organized and easier to read. Below, the same example now using a local variable to define the packages that should be installed

packages = ['vim', 'git', 'ntp']

packages.each do |package|

 apt_package package do

   action :install

 end

Recent Comments

No comments

Leave a Comment