Ansible local playbook example (Without a second machine)

Here’s an example of an Ansible playbook that runs tasks on the local machine:

---
- name: Run tasks on localhost
  hosts: localhost
  connection: local

  tasks:
    - name: Print a message
      debug:
        msg: "Hello, Ansible!"

    - name: Install a package
      package:
        name: nginx
        state: present

    - name: Start the nginx service
      service:
        name: nginx
        state: started

In this example, the playbook is targeting the “localhost” machine and using the local connection type to run the tasks on the local machine where Ansible is being executed.

The tasks section contains three tasks:

  • The first task uses the debug module to print a message to the console.
  • The second task uses the package module to install the “nginx” package.
  • The third task uses the service module to start the “nginx” service.

You can save this playbook in a file, for example, local_playbook.yml, and then execute it using the ansible-playbook command:

ansible-playbook local_playbook.yml

Make sure you have Ansible installed on the machine where you want to run this playbook.