Question regarding creating multiple RDS instances and reuse of modules/scripts

I am new to Terraform, but have gone through the tutorial on using Terraform to create AWS RDS instances, and now have a,, etc that I’ve used to successfully create an RDS Postgres database instance with name ‘example’ (for example). I have a use case where I need to be able to create a variable number of instances either all at once (for example, 30 RDS database instances), or one at a time… …i.e. create 5 initial instances, then add one occasionally.
I have tried changing the database name in my to ‘example2’ for example, but running terraform apply after this results in renaming the existing ‘example’ to ‘example2’, a modification, to the existing instance, not a new instance.
I feel I am missing something fundamental in how to reuse my terraform for these scenarios. I’ve gone through the documentation and been unsuccessful so far.

An instance of a resource represents one “thing”, so one instance of the RDS resource is one RDS database server/cluster. If you edit the code that defines that instance you will change the instance in AWS once you do a terraform apply.

If you want multiple RDS servers you need multiple resource instances in the terraform code. There are two ways to achieve that:

  1. Have multiple resource blocks with different details.
  2. Have a single resource block, but use the count or for_each options to create multiple instances

The use of count & for_each are really powerful and cater for the case where you want multiple instances of basically the same thing - usually the definition is pretty similar between instances with only a few things changing (e.g. name, size, etc.)

You might write your code to use a variable (maybe controlled through a tfvars file) or local to set up which instances are created, so adding another instance (or adding 100 more instances) is just a case of adjusting the value of that variable. A simple terraform apply and you have your new instances in AWS. Similarly you can adjust the variable to remove (or change) instances really easily too.

1 Like