Use existing IDs in other main.tf

Hi all!

In an OpenStack environment I have some VMs and security groups created by a main.tf file. In a second step a want to run another main.tf which adds some rules to the SGs. The rules are based on IP addresses that are only available after running the first main.tf. But to create the security rules I have to refer to the already existing security group, which is not defined in my second main.tf.

I managed to fetch the IDs from the terraform.tfstate file using jq, but I fail to import them. Command is:

terraform import openstack_networking_secgroup_v2.foo id-from-tfstate

But when I run this I get ā€œBefore importing this resource, please create its configuration in the root moduleā€.

When I add the mentioned resource to the configuration it says ā€œTerraform is already managing a remote object for openstack_networking_secgroup_v2.foo. To import to this address you must first remove the existing object from the stateā€.

How can I use existing IDs in other main.tfs?

Thanks a lot,
Oliver

It sounds like you are wanting to use data sources rather than resources in the second Terraform stack. Or you could use the remote state data source with outputs from the first stack.

1 Like

That sounds like a solution to the problem, but IĀ“m not too sure about how to use that in my case.

LetĀ“s say I have two folders ā€œEnv-Aā€ and ā€œEnv-Bā€ - in each folder is a main.tf and Env-A is containing the declaration of a resource ā€œRes-Aā€ which I want to refer to in ā€œEnv-Bā€. How would that look like?

Edit: Guess I found it. Will test that out and post here if it works. Thanks for givingme that hint, stuart-c. :slight_smile: