使用ansible将数据插入mysql表 [英] Insert data into mysql tables using ansible

查看:86
本文介绍了使用ansible将数据插入mysql表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该有一些体面的方式使用 ansible 来处理 mysql 数据库,例如将数据插入表中或在 mysql db 上运行任何命令.

我知道有一些模块可以创建数据库、管理复制、用户和变量:

  • mysql_db - 从远程主机添加或删除 MySQL 数据库.
  • mysql_replication (E) - 管理 MySQL 复制
  • mysql_user - 从 MySQL 数据库中添加或删除用户.
  • mysql_variables - 管理 MySQL 全局变量

我的用例场景是,我已经在 ubuntu 上安装了 mysql-server 并成功创建了数据库,现在我必须将数据插入表中并想知道是否有办法实现它通过 ansible.

解决方案

解决方案 1:

我认为您错过了 mysql_db 模块的导入功能.您可以使用 import 作为参数来加载架构和数据,并为其提供一个文件以在 target

中加载

来自 Ansible 文档的示例:

#将数据库转储文件复制到远程主机并恢复到数据库'my_db'- 复制:src=dump.sql.bz2 dest=/tmp- mysql_db: name=my_db state=import target=/tmp/dump.sql.bz2

解决方案 2:

如果 mysql_db 没有为您提供所需的所有选项和灵活性,您可以将 mysql 程序与 shell 结合使用.

- 名称:导入数据库外壳:mysql db_name <转储文件

以上将dump.sql 文件加载到数据库db_name 中.更多选项参见 mysql 程序手册:man mysql

解决方案 3:

mysqlimport 实用程序与 command 模块:

- 名称:导入数据库命令:mysqlimport [选项] db_name textfile1 [textfile2 ...]

参见:mysqlimport 文档

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.

解决方案

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

这篇关于使用ansible将数据插入mysql表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆