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?

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.

Comments

Got any thoughts on what you've just read? Anything wrong, or no longer correct? Sign in with your GitHub account to leave a comment.

(All comments get added as Issues in our GitHub repo here, using the comments tool Utterances)