Skip to content

Instantly share code, notes, and snippets.

@rmkraus
Last active March 15, 2024 03:37
Show Gist options
  • Save rmkraus/60a90e140916ae765cacfad61d0b140f to your computer and use it in GitHub Desktop.
Save rmkraus/60a90e140916ae765cacfad61d0b140f to your computer and use it in GitHub Desktop.
Ansible Automation for Static DHCP Entries on UniFi Gear
#!/usr/bin/ansible-playbook
# more api documentation here:
# https://ubntwiki.com/products/software/unifi-controller/api
---
- name: test unifi api
hosts: localhost
gather_facts: no
vars:
unifi_user: SVC_ACCT_USERNAME
unifi_pass: SVC_ACCT_PASSWORD
unifi_host: ubnt.example.com:8443
unifi_site: default
mac_address: aa:aa:aa:aa:aa:aa
ip_address: 192.168.10.100
tasks:
- name: login
uri:
url: https://{{ unifi_host }}/api/login
method: POST
validate_certs: no
body:
username: "{{ unifi_user }}"
password: "{{ unifi_pass }}"
remember: false
strict: false
body_format: json
register: unifi_login
- debug:
msg: "{{ unifi_login }}"
verbosity: 1
- name: get host id
uri:
url: https://{{ unifi_host }}/api/s/{{ unifi_site }}/stat/user/{{ mac_address }}
method: GET
validate_certs: no
headers:
Cookie: "{{ unifi_login.set_cookie }}"
register: unifi_meta
- debug:
msg: "{{ unifi_meta }}"
verbosity: 1
- name: set host ip
uri:
url: https://{{ unifi_host }}/api/s/{{ unifi_site }}/rest/user/{{ unifi_meta.json.data.0._id }}
method: PUT
validate_certs: no
headers:
Cookie: "{{ unifi_login.set_cookie }}"
body:
fixed_ip: "{{ ip_address }}"
network_id: "{{ unifi_meta.json.data.0.network_id }}"
use_fixedip: true
body_format: json
when: "'fixed_ip' not in unifi_meta.json.data.0 or unifi_meta.json.data.0.fixed_ip != ip_address"
register: unifi_action
changed_when: unifi_action.status == 200
- name: logout
uri:
url: https://{{ unifi_host }}/api/logout
method: POST
validate_certs: no
headers:
Cookie: "{{ unifi_login.set_cookie }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment