Question

I'm using Ansible to configure and deploy an EC2 instance, which is running MongoDB.

I'm wondering now how can I configure MongoDB to be restarted automatically, after the EC2 instance is being rebooted. Or do I simply have to re-run the Ansible Playbook?

This is my current Ansible Playbook:

- hosts: staging_mongodb
  user: ec2-user
  sudo: yes

  vars_files:
    - vars/mongodb.yml

  tasks:
    - name: Check NTP
      action: service name=ntpd state=started

    - name: Copy MongoDB repo file
      action: copy src=files/10gen.repo dest=/etc/yum.repos.d/10gen.repo

    - name: Install MongoDB
      action: yum pkg=mongo-10gen state=latest

    - name: Install MongoDB server
      action: yum pkg=mongo-10gen-server state=latest

    - name: Template the MongoDB configuration file
      action: template src=templates/mongod.conf.j2 dest=/etc/mongod.conf

    - name: Prepare the database directory
      action: file path=${db_path} state=directory recurse=yes owner=mongod group=mongod mode=0755

    - name: Configure MongoDB
      action: service name=mongod state=started enabled=yes
Was it helpful?

Solution

In this specific example, the simplest way would be in the last block to change state=started to state=restarted.

From Ansible's service module documentation:

started/stopped are idempotent actions that will not run commands unless necessary. restarted will always bounce the service. reloaded will always reload.

However, according to Ansible's best practices, you should consider using 'handlers' so that your MongoDB restarts only when necessary.:

tasks:
  - name: Template the MongoDB configuration file
    action: template src=templates/mongod.conf.j2 dest=/etc/mongod.conf
    notify:
      - restart mongodb

  - name: Prepare the database directory
    action: file path=${db_path} state=directory recurse=yes owner=mongod group=mongod mode=0755
    notify:
    - restart mongodb

  - name: Configure MongoDB
    action: service name=mongod state=started enabled=yes

handlers:
  - name: restart mongodb
    service: name=mongodb state=restarted

Handlers are only fired when certain tasks report changes, and are run at the end of each play so you will not be restarting your MongoDB more than necessary.

Finally, instead of using yum pkg=mongo-10gen state=latest, consider using specific package versions. With something as important as a database, you really do not want to have different package versions running each time you build a new server and/or don't want to be surprised when 10gen unexpectedly releases a new version that negatively affects you. Use a variable with package name-version and just update it when you are ready to migrate to a new version.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top