Search code examples
chef-infrachef-recipecookbookrhel7

Changing directory within Chef Recipe


This is my first attempt at writing a chef cookbook. I'm attempting to write a recipe that will automatically install git, make a new directory (git_repo/), change to that directory, initialize to be a git repository, and then connect to the remote git repository once I run chef-client on my node. I got it to install git and make the directory but I am unsure how to write within the recipe to change directory to git_repo. the code I have is

package 'git' do
  action :install 
end 

directory '/home/git_repo' do   
  mode 0755   
  owner 'root'   
  group 'root'   
  action :create 
end

execute 'change' do
  command "sudo cd git_repo" 
end

Is there a better resource type to use besides execute for this particular action? If so, could someone elaborate on it?


Solution

  • The execute resource as a property cwd:

    cwd: The current working directory from which a command is run.

    In order to run a command from within the git_repo/ directory as working dir, use the following declaration:

    execute 'init' do
      command "git init"
      cwd "/home/git_repo"
    end
    

    As this would very likely fail on the second chef run (because git init will not succeed), you should guard this resource using the creates property:

    creates: Prevent a command from creating a file when that file already exists.

    execute 'init' do
      command "git init"
      cwd "/home/git_repo"
      creates "/home/git_repo/.git"
    end
    

    As a general note, I am not sure, if you really want to initialize an empty repository. If you just want to clone a repository, use the git resource.