Can cdktf commands be executed inside python code?

324 Views Asked by At

I am using cdktf for provisioning my resources using Python and Terraform. I want to automate this entire process and hence, asking for the "cdktf deploy" to be part of the python code, as below:

from constructs import Construct
from cdktf import App, TerraformStack
from imports.azurerm import AzurermProvider, ResourceGroup
import subprocess


class MyStack(TerraformStack):
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        # define resources here
        loca="West Europe"
        rg_name="example-rg1"
        tag = {
            "ENV": "Dev",
            "PROJECT": "AZ_TF"
        }
        AzurermProvider(self, "Azurerm", \
                        features={}
                        )

        example_rg = ResourceGroup(self, 'example-rg1', \
                                   name=rg_name,
                                   location = loca,
                                   tags = tag
                                   )

app = App()
name = "cdktf5"
MyStack(app, name)
app.synth()
subprocess.run(["cdktf", "deploy"])

However, this does not work as expected, with the following output:


⠼ synthesizing...

⠙ synthesizing...

⠇ synthesizing...

⠸ synthesizing...

⠇ synthesizing...

⠦ synthesizing...

Needless to say, the resources are not created.

2

There are 2 best solutions below

1
On

Try subprocess.run(["cdktf", "deploy", "--skip-synth"]) instead of subprocess.run(["cdktf", "deploy"])

0
On

No cdktf commands can not execute within the CDKTF program. You would need a separate python file that runs deploy. The reason is the program you are executing is calling itself, creating an infinite loop. Your cdktf program is invoked as part of the synth step by the CDKTF CLI on plan/apply/synth operations. This means when you start a process from that program you start it again through the CDKTF CLI.