How to Run an Ansible Playbook

A playbook describes a set of tasks that you want Ansible to perform. You can use a playbook to get Ansible to apply configuration to remote systems, like virtual servers. But how do you actually run a playbook?

In this article we’ll see the most basic task in Ansible – running a playbook.

To run a playbook, start by installing Ansible first. It includes the ansible-playbook command. You won’t get far without that.

Then, you can run a playbook like this (assuming that your playbook is called playbook.yml, but you might call it something more exciting):

ansible-playbook playbook.yml

But.

You probably want to run your playbook against some hosts, right? And for that, you want an inventory file.

See an example playbook

If you want a really simple example Ansible playbook that you can use to try out these commands, fork our Git repo here:

See a simple Ansible playbook on GitHub

Let’s see how to set an inventory file when you run a playbook.

Specifying an inventory file

Ansible works with an inventory file. It contains a list of hosts. You then tell Ansible to run a playbook on the hosts in the inventory file.

An inventory file might look like this:

myhost.example.com
sophie.example.com

[greenservers]
forest-green.example.com
bathroom-green.example.com

By default, Ansible will look in /etc/ansible/hosts for an inventory file.

If you haven’t put an inventory file there, you will probably want to specify the location of an inventory file manually, when you run the playbook. So, you can use the -i option to do that:

ansible-playbook -i /path/to/inventory_file site.yml

And next we’ll look at another really common thing you want to do when running playbooks, which is to set some variables.

Want to override variables in a playbook? Use --extra-vars

Sometimes you want to run a playbook, with some extra variables. Maybe you want to override some vars in the playbook, like a password or port number.

When you want to set some variables at the command line, you can pass the --extra-vars option to ansible-playbook:

ansible-playbook -i hosts --extra-vars "person=Dave" site.yml

Give it a go

Don’t forget that if you want to try these commands out, clone the example playbook in the Git repo (see the button above) and give it a go.

Tom Donohue

By Tom Donohue, Editor | Twitter | LinkedIn

Tom is the founder of Tutorial Works. He’s an engineer and open source advocate. He uses the blog as a vehicle for sharing tutorials, writing about technology and talking about himself in the third person. His very first computer was an Acorn Electron.

Join the discussion

Got some thoughts on what you've just read? Want to know what other people think? Or is there anything technically wrong with the article? (We'd love to know so that we can correct it!) Join the conversation and leave a comment.

Comments are moderated.