Self Hosting

Taming Dynamic IPs: Automating Proxmox LXC Setup with Terraform, Ansible, and DHCP

So, you’re like me, happily homelabbing for years. I’ve been using Proxmox LXCs and recently started automating things with Terraform and Ansible. I hit a snag, though, when trying to integrate these tools with my existing DHCP setup managed by OPNsense.

My goal was simple: spin up new LXCs with Terraform (OpenTofu), grab their dynamically assigned IP addresses, and then hand those IPs over to Ansible to complete the configuration. Sounds straightforward, right? Well, it wasn’t as easy as I thought.

The DHCP Dilemma

Terraform successfully created the LXCs, but the state file and terraform status only showed “dhcp” for the IP address. Not very helpful for Ansible, which needs the actual IP to connect! I needed a way to bridge this information gap.

Finding the Missing IP

Here’s the solution I came up with. Since Proxmox’s API exposes information about running VMs and containers, including their network interfaces and assigned IPs, I decided to use a small script within my Terraform configuration. After the LXC creation, this script queries the Proxmox API. It retrieves the dynamically assigned IP address. Then, it outputs this IP as a Terraform output variable.

Connecting the Dots with Ansible

Now Ansible enters the picture. By referencing the Terraform output variable, Ansible can access the dynamically assigned IP address. With that information, Ansible can connect to the newly created LXC and perform the rest of the setup, such as installing software, configuring users, and more.

Example Workflow

  • Terraform: Creates the LXC in Proxmox, then runs a script to fetch the IP address from the Proxmox API and outputs it.
  • Ansible: Uses the IP address provided by Terraform to connect to the LXC and complete the setup.

Key Benefits

This approach provides several advantages:

  • Automation: Streamlines the entire LXC creation and configuration process.
  • Flexibility: Works seamlessly with existing DHCP setups.
  • Centralized Management: All IP addresses are managed through OPNsense.

Challenges and Further Considerations

While this solution worked well for me, there are some things to keep in mind. Depending on your environment and setup, you may encounter some differences in Proxmox API responses. You’ll need to tailor the script to suit your specific use case. You may also want to consider error handling and retry mechanisms to ensure robustness. Additionally, securing communication between Terraform, Ansible, and Proxmox is crucial.

This approach has made my homelab much more manageable. I hope this helps you on your automation journey as well! Let me know in the comments if you have any questions.

Leave a Reply

Your email address will not be published. Required fields are marked *