This repo contains an example of how to import resources in Terraform with the vSphere provider.
The goal is to automatically generate a file with the required import blocks for Terraform to import resources. The import.py is a Python script that communicates with the vCenter API and returns a list of VMs according to a specified filter string.
- Python: version 3.13.3 was used for this demo.
- Terraform: version used: 1.11.3
git clone https://github.com/tf-demos/config-import-example.git import-exampleUpdate the .env file with the corresponding host, username and password to authenticate to vCenter. Once done, remove the .example from the file name:
cd import-example/python
# Update the .env file accordingly
mv .env.example .envpython -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtThis script generates an imported.tf file with the necessary import blocks for Terraform. It retrieves a list of VMs for a specified resource pool in vCenter called "Demo Workloads", you can change that directly in the python code.
And additionally uses a "filter string" that filters the VMs to import according to the name. This parameter must be passed as a command line argument. For example, in this case the filter is database:
python import.py databaseUpon successfully running the script, this will generate an imported.tf file inside import-resource.
cd ../import-resources
terraform init
terraform plan
Once you have imported resources in Terraform you can manage them, modify them, and destroy them.
deactivate