This article explores defining and capturing outputs in CDKTF, specifically how to output file contents like a README file.
In this article, we explore how to define and capture outputs in CDKTF. Outputs in CDKTF are created by instantiating the TerraformOutput class, which is equivalent to using output blocks in Terraform’s HashiCorp Configuration Language. This guide demonstrates how to output file contents, such as a README file, using CDKTF.
The approach demonstrated here mirrors Terraform’s output blocks but leverages the CDKTF framework to integrate outputs directly within your codebase.
To output the contents of a README file, instantiate the TerraformOutput class as shown below. This example creates an output named readMeContent that captures the content of the README file:
Copy
Ask AI
// Output the readMeFile contentnew TerraformOutput(this, 'readMeContent', { value: readMeFile.content,});
A common practice is to define outputs at the end of the file. In this example, we first create a file resource. Below is the code that creates a package.json file:
To capture the README file content as an output, ensure that you pass a proper scope to the TerraformOutput constructor. Start by creating the README file resource:
Copy
Ask AI
const projectDirectory = path.join(process.env.INIT_CWD!, './authors-projects');const projectName = `project-1`;const basePath = `${projectDirectory}/${projectName}`;// Add a README fileconst readmeFile = new file.File(this, 'readme-file', { filename: `${basePath}/README.md`, content: `# ${projectName}\n\nThis is the ${projectName} project`,});// Sample content: # project-1\n\nThis is the project-1 project.// ToDo: Create the package.json file as wellnew file.File(this, 'package-json-file', { filename: `${basePath}/package.json`, content: JSON.stringify({ name: projectName, version: '1.0.0', main: 'index.js', scripts: { start: 'node index.js', }, }),});
Now, output the content of the README file by using its content property:
Copy
Ask AI
new TerraformOutput(this, 'readMeContent', { value: readmeFile.content,});
After rerunning the deploy command, you should see output similar to the following:
Copy
Ask AI
cdktf-project-builderlocal_file.package-json-file: Creating...local_file.package-json-file: Creation complete after 0s [id=b60a2ad91f16bfeb7fe2]cdktf-project-builderApply complete! Resources: 1 added, 0 changed, 0 destroyed.root in ~/code via ⬢ v20.17.0 on ⬢ (us-east-1) took 20syarn cdktf deploy
This confirms that the output readMeContent now correctly references the content of the README file.
This section demonstrated how to define outputs in CDKTF by capturing the content of a README file. By following these steps, you ensure that your outputs correctly mirror the behavior of Terraform’s native output blocks.Next, we will explore constructs in CDKTF to further enhance your infrastructure code management.For more details, refer to the CDK for Terraform Documentation.