How to store Terraform output


I have created an EC2 instance with terraform CDK in TS. By using terraform output i am getting private or public IPs for created instance as shown below. How to store these values in any variable or any Db or somewhere else ?

const instance = new EC2.Instance(this, name, config)
new TerraformOutput(this, 'private Ip', {
    value: instance.privateIp

Hi @vishalailani :wave:

There are multiple ways which depend on where and how you want to use the IP after the EC2 instance has been created.
Can you give some more context?


Hi @ansgarm , i want to pass this private IP to an API as argument for some further operations, so i need to store that somewhere. can you help ?

Hi @vishalailani!

This depends on how your API is set up. A simple possibility is to use Terraform to write a file that can then be consumed by the API. I’ve done this here for a statically built frontend.
If your API supports getting the API endpoint at runtime you could also store it in the AWS Parameter Store and have the API read it from there.
There are a lot more possibilities that all depend on how your systems are built and on what you want to achieve. An alternative could also be to create and update a DNS record for your IP and use the DNS name in your API instead.

Hi @ansgarm !

I have tried Terraform file approach and it is storing output in a file but to read this file i also has to use Terraform (new DataLocalFile). Is there any way so that i. can read the file without triggering Terraform stack because if i go into terraform it perform init, plan apply and all but i don’t want. i just want to read and pass this output to my API which is not related to Terraform ?

This is how i am getting output in file.

 new LocalProvider(this, "sample-provider", {
      alias: "sample"

    new File(this, 'sampleFile', {
      filename: "sample",

And this is how i am reading the output but if i just console it is giving an encoded string so i have to use TerraformOutput which i don’t want.

    const content = new DataLocalFile(this, 'sampleFileData', {
      filename: 'sample'
    new TerraformOutput(this, 'PrivateIp1', {
      value: content.content


@vishalailani why not just read the file in directly via fs.readFileSync or similar?

Yeah was trying fs.readFile initially but not getting output because of async process but fs.readFileSync worked for me.
Thank you so much @jsteinich