Subha_26
Subha_26

Reputation: 450

Can cdktf commands be executed inside python code?

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.

Upvotes: 0

Views: 468

Answers (2)

ut001
ut001

Reputation: 1

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

Upvotes: 0

Daniel Schmidt
Daniel Schmidt

Reputation: 11921

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.

Upvotes: 0

Related Questions