What is the difference between an Ansible playbook and an Ansible role?

An Ansible playbook is a set of instructions written in YAML that define a set of tasks to be executed on a given set of hosts. It is used to configure systems, deploy applications, and perform other IT automation tasks.

An Ansible role is a collection of related tasks, templates, files, variables, and handlers that can be used to create a playbook. It is designed to be reusable and can be shared with other users.

Example:

Ansible Playbook:


– hosts: all
become: true
tasks:
– name: Install Apache
apt: name=apache2 state=installed
– name: Start Apache
service: name=apache2 state=started

Ansible Role:


– name: apache
hosts: all
become: true
tasks:
– name: Install Apache
apt: name=apache2 state=installed
– name: Start Apache
service: name=apache2 state=started
handlers:
– name: restart apache
service: name=apache2 state=restarted

What is the difference between a playbook and a role in Ansible?

Playbooks are a set of instructions written in YAML that define a set of tasks to be performed by Ansible. They are written to be reusable, maintainable, and easily understood. Playbooks can be used to configure systems, deploy applications, or manage complex workflows.

Roles are a way to group related tasks, files, and variables into one container. Roles are organized in a specific directory structure, and contain all the necessary components for a specific task, such as tasks, handlers, files, templates, and variables.

For example, a playbook might contain a role to install a web server. This role would include tasks to install the web server, configure it, and start it. It would also include files, templates, and variables needed to complete the task.