1

I am using cdktf in Python and maintaining multiple stacks using Terraform and the states are being stored in azure storage account as backend. I would need to fetch any stack at any point in time and make changes to the resources in the stack. However, I do not maintain the state locally. How can I fetch the state from azure backend and then make changes to the resources in the stack?

Subha_26
  • 440
  • 4
  • 14
  • What exact problem are you running into? Your question about downloading the state and updating resources is exactly what the `cdktf deploy` command accomplishes every time you run it. – Mark B Mar 27 '22 at 18:44
  • @MarkB For the cdktf deploy to work, I need to have the .tf.json file with me, which I don't have. It purely exists in the remote backend. How can I fetch it from backend? – Subha_26 Mar 27 '22 at 18:56
  • Basically at the time of terraform init, I do not have the state file of a previous deployment. I need to tell terraform the state file is available in the azure backend. – Subha_26 Mar 27 '22 at 19:01
  • If you have the Terraform backend configured, Terraform automatically downloads that file from the backend every time you run Terraform. If it didn't do that, then what would be the point of the backend configuration? – Mark B Mar 27 '22 at 19:17
  • @MarkB I am using the following commands: terraform init -backend-config=config.backend.tfbackend After this, how to pull the state from remote? Please note that I do not have the .tf or .tfstate file in my local. – Subha_26 Mar 29 '22 at 18:14
  • As I've stated already, every terraform command you run will automatically download a temporary copy of the state file from the backend. All you have to do is configure the backend, which you've already done. You don't also have to manually download the file from the backend. If you did, what would be the point? – Mark B Mar 29 '22 at 19:56

1 Answers1

1

If I get you correctly you want to configure the backend to use Azure. In Terraform CDK this is done via constructs, there is a AzurermBackend you can use.

This is the example from the CDKTF repo

import { Construct } from "constructs";
import { App, TerraformStack, AzurermBackend } from "cdktf";

class MyStack extends TerraformStack {
  constructor(scope: Construct, name: string) {
    super(scope, name);


    // Azurerm Backend - https://www.terraform.io/docs/backends/types/azurerm.html
    new AzurermBackend(this, {
      resourceGroupName: "StorageAccount-ResourceGroup",
      storageAccountName: "abcd1234",
      containerName: "tfstate",
      key: "prod.terraform.tfstate",
    });

    // define resources here
  }
}

const app = new App();
new MyStack(app, "typescript-backends");
app.synth();

Once you have this configured, every cdktf deploy or cdktf destroy will run using this backend.

Daniel Schmidt
  • 11,605
  • 5
  • 38
  • 70