Insert data into mysql tables using ansible

There should be some decent way to work with mysql databases using ansible like inserting data into tables or any command to run on mysql db.

I know there are modules to create db, manage replications, user and variables:

  • mysql_db – Add or remove MySQL databases from a remote host.
  • mysql_replication (E) – Manage MySQL replication
  • mysql_user – Adds or removes a user from a MySQL database.
  • mysql_variables – Manage MySQL global variables

My use case scenario is, I’ve installed mysql-server on ubuntu and created the database successfully and now I have to insert data into the tables and wondering if there is a way to achieve it via ansible.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Solution 1:

I think you missed import functionality of mysql_db module. You can load both schema and data with it using import as parameter to state and giving it a file to load in target

Example from Ansible docs:

# Copy database dump file to remote host and restore it to database 'my_db'
- copy: src=dump.sql.bz2 dest=/tmp
- mysql_db: name=my_db state=import target=/tmp/dump.sql.bz2

Solution 2:

If mysql_db does not give you all options that you need and flexibility you can just use mysql program in combination with shell.

- name: Import DB 
  shell: mysql db_name < dump.sql

Above loads dump.sql file into database db_name. See mysql program manual for more options: man mysql

Solution 3:

mysqlimport utility with command module:

- name: Import DB 
  command: mysqlimport [options] db_name textfile1 [textfile2 ...]

See: mysqlimport docs

Method 2

You can use mysql_db module. Its state: parameter has values of present, absent, dump, import. If it is set to import, then you can use target: parameter to indicate location, on the remote host, of the dump file to read from. Uncompressed SQL files (.sql) as well as bzip2 (.bz2) and gzip (.gz) compressed files are supported.

# Copy database dump file to remote host and restore it to database 'my_db'
- copy: src=dump.sql.bz2 dest=/tmp
- mysql_db: name=my_db state=import target=/tmp/dump.sql.bz2


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x