How Can I Use Terraform to Change the Power State of a Linode?

Linode Staff

Hi,
I am trying to manage the power cycle (i.e reboot, start, shut down) the instance through terraform. Is there anyway that we can achieve that. Can you please help me with that ?

1 Reply

Since Terraform and the Linode Terraform Provider don't offer a way to do this out of the box, the easiest way to set this up is to create a null resource that uses either the Linode CLI or API to change the state.

In my example below, I'll be using the Linode CLI to create a null resource called reboot_instance which can be used to reboot the instance created with Terraform. If you haven't already, you'll also need to download and configure the Linoode CLI. You can check out our Using the Linode CLI to set that up.

Once that's installed and configured, all you'll need to do is add the following resource to the end of your .tf file, replacing both instances of ${type.local-name.id} using the type and local name for the resource you want to manage.

resource "null_resource" "reboot_instance" {

  provisioner "local-exec" {
    on_failure  = fail
    interpreter = ["/bin/bash", "-c"]
    command     = <<EOT
        echo -e "\x1B[31m Warning! Restarting instance having id ${type.local-name.id}.................. \x1B[0m"
        linode-cli linodes reboot ${type.local-name.id}
        echo "***************************************Rebooted****************************************************"
     EOT
  }
#   this setting will trigger script every time,change it something needed
  triggers = {
    always_run = "${timestamp()}"
  }
}

Once that's been added to your .tf file, you'll want to run terraform apply to update the state which will reboot the Linode. After the first apply, you can then run terraform apply -target null_resource.reboot_instance to reboot in the future. For other jobs such as shutting down or powering off, all you'll need to do is change the name of the null resource and the Linode CLI command. You can find more information about the CLI commands in the Linode API/CLI Documentation.

Reply

Please enter an answer
Tips:

You can mention users to notify them: @username

You can use Markdown to format your question. For more examples see the Markdown Cheatsheet.

> I’m a blockquote.

I’m a blockquote.

[I'm a link] (https://www.google.com)

I'm a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct