Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have ansible execute a task only when my database is created?

Tags:

ansible

I have a migration step I need to fake after the database has been bootstrapped and it looks something like this:

- name: "Setup database"
  mysql_db: name=my_database state=present target=/tmp/database.sql
  args:
    login_user: root
    login_password: ""

- name: Import the database
  shell: ../../vendor/bin/propel up --fake
  args:
    chdir: /var/www/project/application/propel

It would obviously not be a good idea to fake migrate the database after the first time. How can I make it only happen once?

like image 990
Kit Sunde Avatar asked Jan 15 '15 19:01

Kit Sunde


3 Answers

So, if I understood right you want Import the database to be run only when Setup database has added a database. Registering a variable in Setup database and using it with when condition in Import the database will do it:

- name: "Setup database"
  mysql_db: name=my_database state=present target=/tmp/database.sql
  args:
    login_user: root
    login_password: ""
  register: db_created

- name: Import the database
  shell: ../../vendor/bin/propel up --fake
  args:
    chdir: /var/www/project/application/propel
  when: db_created.changed
like image 143
Pasi H Avatar answered Oct 12 '22 23:10

Pasi H


I liked both of these answers and used them to do the following, which for me was a much cleaner solution. It's a pity the task repeats but it works as you'd expect, the import only happens if the database had to be created.

- name: Create DB (if necessary)
  mysql_db:
    name=my_database
    state=present
  register: db_created

- name: Import DB (if it was created)
  mysql_db:
    name=my_database
    state=import
    target=/tmp/database.sql
  when: db_created.changed
like image 36
Stephen O'Flynn Avatar answered Oct 13 '22 01:10

Stephen O'Flynn


Pasi has already given you the answer of your question, but even if you want to skip the database creation step if it already exists, you can even add the check to it, like this:

- name: check if DB exists
  shell: mysql -e 'SHOW DATABASES;' | grep my_database
  register: dbstatus
  ignore_errors: True

- name: "Setup database"
  mysql_db: name=my_database state=present target=/tmp/database.sql
  args:
    login_user: root
    login_password: ""
  register: db_created
  when: dbstatus.rc != 0

- name: Import the database
  shell: ../../vendor/bin/propel up --fake
  args:
    chdir: /var/www/project/application/propel
  when: db_created.changed

Hope this will help you. Thanks

like image 36
Arbab Nazar Avatar answered Oct 13 '22 01:10

Arbab Nazar