chef-infracookbook

Understanding chef cookbook snippet


I am not able to interpret the below code in Chef cookbook:

systemd_unit '<service_name>' do      
   action %i[enable start]
end

I read about systemd_unit from systemd_unit resource. However, how is action determined here? I am trying to convert this cookbook to ansible and wanted to understand whats happening in cookbook first.

Also, being new to cookbook, I also wanted to confirm if:

include_recipe '<cookbook_name>'

is provided then my understanding is, it includes default.rb from the given cookbook and other recipes within that cookbook are not included. Please let me know, if that's correct.


Solution

  • Providing an expanded answer in addition to the answer by @Psyreactor.

    Actions in a Chef recipe are represented by Ruby symbols, like :create, :start, etc. When multiple actions are to be performed on the same resource, they are passed as an array.

    So instead of writing two resource declarations for the same service like this:

    # Enable the service
    systemd_unit '<service_name>' do 
      action :enable
    end
    
    # Start the service
    systemd_unit '<service_name>' do 
      action :start
    end
    

    It can be written as one:

    # Enable and start the service
    systemd_unit '<service_name>' do 
      action [ :enable, :start ]
    end
    

    Note: %i is a way to omit the use of : character and create an array of symbols. %i(enable, start) is the same as [ :enable, :start ].

    Chef "actions" are known as "state" in Ansible. So for a similar service in Ansible, you would do:

    systemd:
      name: '<service_name>'
      enabled: yes
      state: 'started'
    

    it includes default.rb from the given cookbook and other recipes within that cookbook are not included.

    That's correct. However, other recipes from that cookbook not getting included in the run depends on that default.rb.