Technology Inside Out!

Index ¦ Archives ¦ Atom ¦ RSS

Running A Python Script Using Chef

Chef is an amazing configuration management tool, widely used in a lot of industries. If you are not familiar with how to run chef/chef-solo, please go through this article first. One of the best feature of Chef is it’s collection of resources. Resources allows Chef to handle configuration of the designated server. Resource have their predefined task like to run a command, to copy a file, to use a template etc. In this article we are going to talk about script resource. This is going to run any script, it could be bash, python or perl. There are separate resources for these scripts.

You put the resources in your recipe. Here is a simple bash script example:

bash "install_something" do
 user "root"
 cwd "/home"
 code <<-EOH
 echo Hello World! ls

As you can see, the bash resource will run the script in the code section and will print “Hello World” to the terminal and the content of /home directory.

So, when you are going to run a python script, the first choice to come to mind is “python” script resource. But there is a limitation to script resources. They only run in-line scripts. Meaning you will have to write the whole script in the code section and it will be executed one line at a time. But you can’t run an external script. Here comes the “execute” resource to rescue!

To run an external script, the structure of the execute resource is:

filename = ""

execute 'execute_file' do
 cwd '/home/peeyush'
 command "python #{static}"

Here the filename contains the name of the script. Then in the execute block, we have cwd which represents the current working directory. This is the directory where the script is present. Then the “command” tells the shell to execute the script. Just put the above lines in your recipe, edit according to the ouput you want and let chef run the script for you! Here is the sample

Screenshot from 2014-03-18 15:19:33.png

As you can see, I am printing “Hello, chef!” and redirecting some out to a text file. Redirection is needed because Chef will just execute the script and won’t show you the output, until it’s an error. Here is what the recipe look like:

Screenshot from 2014-03-18 15:15:20.png

Remember to change the current working directory (cwd) according to your setup.Everything else is same as previous article and you can test it out using chef-solo.

Screenshot from 2014-03-18 15:18:51.png

© The Geeky Way. Built using Pelican. Theme by Giulio Fidente on github.

Disclaimer Privacy policy