ansible small example , one play book call 3 roles - unix1998/technical_notes GitHub Wiki

an Ansible playbook that calls three roles, where each role simply prints a message. Each role will be executed on the localhost.

Directory Structure

ansible/
├── playbook.yml
├── roles/
│   ├── role1/
│   │   └── tasks/
│   │       └── main.yml
│   ├── role2/
│   │   └── tasks/
│   │       └── main.yml
│   └── role3/
│       └── tasks/
│           └── main.yml

Step-by-Step Instructions

  1. Create the directory structure as shown above.
  2. Create the playbook file: playbook.yml
  3. Create the role files: main.yml under each role directory.

Here are the detailed contents for each file.

playbook.yml

---
- name: Run multiple roles to print messages
  hosts: localhost
  become: false
  roles:
    - role1
    - role2
    - role3

roles/role1/tasks/main.yml

---
- name: Print message from role1
  debug:
    msg: "Hello from role1"

roles/role2/tasks/main.yml

---
- name: Print message from role2
  debug:
    msg: "Hello from role2"

roles/role3/tasks/main.yml

---
- name: Print message from role3
  debug:
    msg: "Hello from role3"

Running the Playbook

  1. Navigate to the directory containing the playbook.yml file.
  2. Run the playbook with the following command:
ansible-playbook playbook.yml

Expected Output

When you run the playbook, you should see output similar to the following:

PLAY [Run multiple roles to print messages] **********************************

TASK [Gathering Facts] ********************************************************
ok: [localhost]

TASK [role1 : Print message from role1] ***************************************
ok: [localhost] => {
    "msg": "Hello from role1"
}

TASK [role2 : Print message from role2] ***************************************
ok: [localhost] => {
    "msg": "Hello from role2"
}

TASK [role3 : Print message from role3] ***************************************
ok: [localhost] => {
    "msg": "Hello from role3"
}

PLAY RECAP ********************************************************************
localhost                  : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

This output shows that each role was executed successfully and printed its respective message.