Using tags for each role

I normally put a tags for each role, so it makes me easier to choose what I need to do for my hosts with only one tag. Then if I need to specify something inside the role, I can specify a second tag and apply both tags easily.

So for example I have here frontend.yml playbook with two roles. Each role deploys one application and each of them has its own tag name:

- name: "Deploy of frontend applications: frontend1, frontend2"
  hosts: frontend
  roles:
    - { role: frontend1,
        tags: frontend1 }
    - { role: frontend2, 
        tags: frontend2 }

So then I can easily choose what I want to do if I run:

ansible-playbook -i inventory/prod frontend.yml -t frontend1
ansible-playbook -i inventory/prod frontend.yml -t frontend2

Then, imagine that inside each playbook, as part of the deployment process, I stop and start my app. Then I can add a tag called restart for that specific tasks. For example inside roles/frontend1/tasks/main.yml:

[...]
- name: Stop {{ service_name }}
  shell: /etc/init.d/{{ service_name }} stop
  tags:
    - restart

- name: Start {{ service_name }}
  shell: /etc/init.d/{{ service_name }} start"
  tags:
    - restart
[...]

Then, you could think that in order to restart the app you could run:

ansible-playbook -i inventory/prod frontend.yml -t frontend1,restart

Sadly you can’t do that because it will restart also frontend2 app. In order to fix that you should add –skip-tags:

ansible-playbook -i inventory/prod frontend.yml -t frontend1,restart --skip-tags frontend2

I know that it doesn’t look really nice, but that’s the best way I’ve found to do it right now. Also I recommend to use an Operation Tool like Rundeck to perform these kind of tasks.

Advertisements

Create a log entry for every Ansible execution

Besides of sending an email when you’re performing a task with Ansible, I also recommend the usage of log files.

- file: path=/var/log/ansible state=touch
- name: "Write into log"
   shell: echo "ANSIBLE | {{ ansible_date_time.iso8601 }} | <USER> | <ACTION> | <WHERE>" >> /var/log/ansible

Then you can easily review that log file with older executions on that server and even send it to a log manager.