Skip to content

Commit

Permalink
ansible: Automate MAC addresses
Browse files Browse the repository at this point in the history
Automate the creation and assignment of random MAC addresses to libvirt
VMs, if the user has not specified one.

Make the MAC addresses reusable by storing them in a `state.ini` file.

Signed-off-by: Dimitris Poulopoulos <[email protected]>
  • Loading branch information
dpoulopoulos committed Jun 21, 2024
1 parent aa486b0 commit c1c53b0
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 5 deletions.
5 changes: 0 additions & 5 deletions ansible/inventory/hosts.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,14 @@ all:
hosts:
node1:
virt_domain_name: node1
virt_domain_net_macaddress: 52:54:00:DD:B9:81
node2:
virt_domain_name: node2
virt_domain_net_macaddress: 52:54:00:0A:B8:82
node3:
virt_domain_name: node3
virt_domain_net_macaddress: 52:54:00:2E:AB:32
node4:
virt_domain_name: node4
virt_domain_net_macaddress: 52:54:00:19:F2:EF
node5:
virt_domain_name: node5
virt_domain_net_macaddress: 52:54:00:6C:BA:E1
admin:
hosts:
boogie:
5 changes: 5 additions & 0 deletions ansible/roles/libvirt-domain/handlers/inventory.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
- name: reload-inventory
ansible.builtin.meta: refresh_inventory
delegate_to: localhost
run_once: true
3 changes: 3 additions & 0 deletions ansible/roles/libvirt-domain/handlers/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---
- name: Handle local inventory
import_tasks: inventory.yml
18 changes: 18 additions & 0 deletions ansible/roles/libvirt-domain/tasks/domain.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,24 @@
qemu-img create -f qcow2 {{ hostvars[virt_host].virt_pool_dir }}/{{ virt_domain_name }}.qcow2 {{ virt_domain_disk_gb }}G
creates: '{{ hostvars[virt_host].virt_pool_dir }}/{{ virt_domain_name }}.qcow2'

- name: Get or create the MAC address variable
delegate_to: '{{ virt_host }}'
set_fact:
virt_domain_net_macaddress:
'{{ virt_domain_net_macaddress |
default("52:54:00" | community.general.random_mac) }}'

- name: Store the MAC address in state.ini
delegate_to: localhost
throttle: 1
notify: reload-inventory
community.general.ini_file:
path: '{{ inventory_dir}}/state.ini'
section: libvirt
option: '{{ inventory_hostname }} virt_domain_net_macaddress'
value: '{{ virt_domain_net_macaddress }}'
no_extra_spaces: true

- name: Define libvirt domain
delegate_to: '{{ virt_host }}'
community.libvirt.virt:
Expand Down

0 comments on commit c1c53b0

Please sign in to comment.