Vikk_King
Vikk_King

Reputation: 131

How to stop/start running ec2 instance via terraform

I have EC2 instance running with web application and this is my POC environment machine. This instance is automated through terraform, But this is running all the time when I don't need it, I want to write the terraform script to poweroff this machine if I don't want to use it so that I can save the cost.

Upvotes: 8

Views: 19680

Answers (3)

Ajinkya Tambe
Ajinkya Tambe

Reputation: 1

To destroy a specific EC2 instance (demo_vm_1), the --target argument can be supplied to the destroy command with the resource path to identify the correct resource as below:

terraform destroy --target aws_instance.demo_vm_1

Upvotes: -1

fahmiduldul
fahmiduldul

Reputation: 1130

There is aws_ec2_instance_state resource to handle ec2 state.

this can be done easily with this code:

resource "aws_instance" "test" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  tags = {
    Name = "HelloWorld"
  }
}

resource "aws_ec2_instance_state" "test" {
  instance_id = aws_instance.test.id
  state       = "stopped"
}

You can also refer documentation here

Upvotes: 8

eatsfood
eatsfood

Reputation: 1088

There are several ways to do this with Terraform. The first solution is to follow the guidance here. It is not the most elegant solution, but it works. You must also keep track of the current state yourself.

If you would like something that is more time-of-day based, like turning on the instance at 06:00 and turning it off at 17:30, then this solution is very good.

Upvotes: 4

Related Questions