0
votes

I have setup basic directory architecture for my ansible playbooks. I have defined two roles:- 1) www:-To manage all the site deployment 2) root :- To do the root related tasks

My root roles contains following tasks:- 1) Setup a new site on target server 2) Start the web server (apache,nginx)

I want to restart my apache server after the site deployment and for that i have created a playbook called apache-restart under tasks for the root roles.This is how my directory structure looks like

enter image description here

This is what i am trying in my site.yml

---

- name: Deploy Application
  hosts: "{{ host }}"
  roles: 
    - www
  become: true
  become_user: www-data
  tags: 
    - site-deployment


- name: Restart Apache Server
  hosts: "{{ host }}"
  roles: 
    - root
  tasks: 
    include: roles/root/apache-restart.yml
  become: true
  become_user: root
  tags: 
    - site-deployment

When i am running this playbook it throwing me this error:-

ERROR! A malformed block was encountered.

The error appears to have been in '/Users/Atul/Workplace/infra-automation/deployments/LAMP/site.yml': line 18, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


- name: Restart Apache Server
  ^ here

is there any better way so that i can directly inclue apache-restart.yml file with my site.yml by specifying root role because if i include only role then ansible will start looking for main.yml.

2

2 Answers

2
votes

tasks should be a list, so:

tasks: 
  - include: roles/root/apache-restart.yml
0
votes

Rename apache-restart.yml to main.yml in root/tasks directory and the tasks specified in that file will be automatically run when you call root role

After renaming the file you can simplify Restart apache server play to

- name: Restart Apache Server
  hosts: "{{ host }}"
  roles: 
    - root
  become: true
  become_user: root
  tags: 
    - site-deployment

Ansible best practice to conditionally restart a server or a daemon is to use handlers

In your case you'd create a handler called Restart Apache Server in www role and notify it in relevant tasks in that role. Using the restart handler in www you can get rid of root role altogether.