Search code examples
javaamazon-web-servicesterraformdevops-services

terraform tf state file for multiple instances


i want to create different instances for different components in aws using terraform.But if i want to destroy specific instances of a component ,it will be destroying all different instances of different components at once , because all share common tfstate file in one folder.So work around is i would need to create different component instances in different folder run terraform for separate tfstate file.Should we need to create separate folder for separate components and run terraform there?

Is there any other work around apart from this?

Thank you


Solution

  • Ok, since there not so much details in the question, let me guess.

    You expect running terraform destroy to destroy some of your 'instances'.

    But you don't want it to destroy ALL your resources.

    You considered separating resources into different folders with different states.

    But this is NOT NEEDED. If you want to destroy some particular 'instance'/'resource' -- just remove it from your config (.tf file) and run terraform apply. This will destroy some 'instance' but keep all other.

    Let's say you have the following config:

    resource "aws_instance" "api" {
      ami           = "${data.aws_ami.ubuntu.id}"
      instance_type = "t2.micro"
    }
    
    resource "aws_instance" "web" {
      ami           = "${data.aws_ami.ubuntu.id}"
      instance_type = "t2.micro"
    }
    
    resource "aws_instance" "app" {
      ami           = "${data.aws_ami.ubuntu.id}"
      instance_type = "t2.micro"
    }
    

    3 instances: web, app, api. You want to destroy web.

    Instead of running terraform destroy, which will destroy all your state, just leave whatever you need and run terraform plan.

    P.S. Separating state in different folders also makes sense. For example, it's very very recommended to separate your different environments into different state files. Furthermore, you can move something more common, like VPC or S3 buckets config into a separate state which will rarely change to not place it under risk when applying some more frequent changes to EC2 instances.