gpt4 book ai didi

database - 使用 terraform 创建数据库模式

转载 作者:行者123 更新时间:2023-12-04 00:21:55 27 4
gpt4 key购买 nike

我使用 aws_db_instance ( main.tf ) 创建了 RDS 实例:

resource "aws_db_instance" "default" {
identifier = "${module.config.database["db_inst_name"]}"
allocated_storage = 20
storage_type = "gp2"
engine = "mysql"
engine_version = "5.7"
instance_class = "db.t3.micro"
name = "${module.config.database["db_name_prefix"]}${terraform.workspace}"
username = "${module.config.database["db_username"]}"
password = "${module.config.database["db_password"]}"
parameter_group_name = "default.mysql5.7"
skip_final_snapshot = true
}

我还可以使用 schema.sql 从文件 terraform apply 创建数据库模式吗?
$ tree -L 1                                                                                               
.
├── main.tf
└── schema.sql

最佳答案

您可以为此使用配置器( https://www.terraform.io/docs/provisioners/index.html ):

resource "aws_db_instance" "default" {
identifier = module.config.database["db_inst_name"]
allocated_storage = 20
storage_type = "gp2"
engine = "mysql"
engine_version = "5.7"
instance_class = "db.t3.micro"
name = "${module.config.database["db_name_prefix"]}${terraform.workspace}"
username = module.config.database["db_username"]
password = module.config.database["db_password"]
parameter_group_name = "default.mysql5.7"
skip_final_snapshot = true

provisioner "local-exec" {
command = "mysql --host=${self.address} --port=${self.port} --user=${self.username} --password=${self.password} < ./schema.sql"
}
}

#Apply scheme by using bastion host
resource "aws_db_instance" "default_bastion" {
identifier = module.config.database["db_inst_name"]
allocated_storage = 20
storage_type = "gp2"
engine = "mysql"
engine_version = "5.7"
instance_class = "db.t3.micro"
name = "${module.config.database["db_name_prefix"]}${terraform.workspace}"
username = module.config.database["db_username"]
password = module.config.database["db_password"]
parameter_group_name = "default.mysql5.7"
skip_final_snapshot = true

provisioner "file" {
connection {
user = "ec2-user"
host = "bastion.example.com"
private_key = file("~/.ssh/ec2_cert.pem")
}

source = "./schema.sql"
destination = "~"
}

provisioner "remote-exec" {
connection {
user = "ec2-user"
host = "bastion.example.com"
private_key = file("~/.ssh/ec2_cert.pem")
}

command = "mysql --host=${self.address} --port=${self.port} --user=${self.username} --password=${self.password} < ~/schema.sql"
}
}
需要在您的设备上安装 mysql 客户端。
如果您无法直接访问您的数据库,还有一个 remote-exec 配置器,您可以在其中使用堡垒主机(首先使用 file 配置器将文件传输到远程位置)。
如果您的架构不是很复杂,您还可以使用 terraform 的 MySQL 提供程序:
https://www.terraform.io/docs/providers/mysql/index.html

关于database - 使用 terraform 创建数据库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59922023/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com