1

I have created EC2 and My sql instance using below code and it executed successfully. what is the procedure if we need to create mysql database in a particular ec2 instance, if there are multiple running.I could see db-instance in aws console . Even though there is option available in console to create database, I need to perform through terraform code.

resource "aws_instance" "DB-Server"
 {
  ami = "ami-051f75c6"
  instance_type = "t2.micro"
  key_name="Key-pair
}
resource "aws_db_instance" "default"
 {
   allocated_storage    = 20
   storage_type         = "gp2"
   engine               = "mysql"
   engine_version       = "5.7"
   instance_class       = "db.t2.micro"
   name                 = "mydb"
   username             = "username"
   password             = "XXXX"
   `enter code here`parameter_group_name = "default.mysql5.7"
}
3
  • I don't understand your question. Are you wanting to specify which EC2 instance to create your MySQL instance on? If so, that really isn't how AWS RDS works. Do you want to do your own MySQL install on an EC2 instance and not use RDS? Commented Mar 22, 2019 at 15:06
  • Hi, yes, i want to install own mysql in EC2 instance. Commented Mar 23, 2019 at 4:34
  • that's not the role of terraform, think about ansible, chef to automation these installation. Commented Mar 25, 2019 at 5:55

2 Answers 2

2

Since you said you would like to install MySQL on your own EC2 instance using Terraform, I would suggest you use the user_data functionality of EC2. User data allows you to define a script to perform installation or configuration of an EC2 instance when it is deployed. Terraform offers hooks into that like so.

resource "aws_instance" "web" {
  ami           = "${data.aws_ami.ubuntu.id}"
  instance_type = "t2.micro"
  user_data = <<-EOF
                #!/bin/bash
                yum install -y mysql56-server
              EOF
  tags = {
    Name = "HelloWorld"
  }
}

Above is a really simple approach to performing the task. You just need to customize the user_data section to your needs.

Sign up to request clarification or add additional context in comments.

Comments

0

You should consider using Terraform local-exec or remote-exec provisioner. It allows you to do anything you could do with bash. When your Terraform code is done bringing up the EC2 instance, you invoke the local/remote exec which runs a script to install MySQL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.