Hey everyone! I’m really excited about today’s topic: getting the IP address of an interface from the OPNsense API. To be honest, I’ve been on a bit of a hunt for reliable and current information on this, but it’s been a bit elusive.
So, I’ve decided to put together this guide in the hopes that it’ll be useful not just for me, but for others who might be in the same boat.
Create user and group
First, you should create a new user and group to grant it only the authorizations it needs.
Access your OPNsense firewall and navigate to System -> Access -> Groups.
Add a new group and name it something like “ApiUsers”. Do not add a member yet, as we are going to create a new one. Save the group and click on “Edit”. Then, open “Assigned Privileges” and select the following: Assigned Privileges
Create a new User, named “api_user”. Set a strong password or select “Generate a scrambled password to prevent local database logins for this user”. Set the Login shell to /usr/sbin/nologin.
Under Group Memberships, select your new ApiUsers Group and assign it to the user.
Save the user and click on “Edit”. Now you will see the option “API keys” for the user - generate a new one.
You will receive a txt file with the following content:
| |
Call the API
First, you need to find the interface you want the IP for, which is most likely your WAN interface.
Navigate to Interfaces -> Overview to see all your interfaces. Search for your desired interface and note the “Device”.
You will need that for the API call.
Here’s a simple bash script to call the API and retrieve the IP of the interface. It utilizes jq, a lightweight and flexible command-line JSON processor.
| |
You can save this as a file and make it executable with chmod +x filename.sh.
You could also use the script above as a one-liner:
| |
There are plenty of use cases. For example, you could avoid calling an external service to get your public IP and update a DNS record if it changed.
However, if you’ve ended up here, you likely already have a specific use case in mind 😉
Photo by Gabriel Heinzer on Unsplash
