NETBOX как dynamic inventory для Ansible — различия между версиями

Материал из megapuper
Перейти к: навигация, поиск
Строка 1: Строка 1:
Подготовим виртуалочку для управления инфрой через ansible
+
Для начала подготовим виртуалочку для управления инфрой через ansible. Использовать будем Debian 12
  
 
+
Ставим python3.11 (т.к. он будет в зависимостях в нашем Pipfile) и pip
Ставим python3.11 (т.к. он в зависимостях в Pipfile) и pip
 
 
  apt install python3.11-full
 
  apt install python3.11-full
 
  apt install pip
 
  apt install pip
Строка 9: Строка 8:
 
Устанавливаем pipenv
 
Устанавливаем pipenv
 
  pip install pipenv --break-system-packages
 
  pip install pipenv --break-system-packages
 +
  
 
Подготавливаем ansible.cfg и Pipfile с зависимостями
 
Подготавливаем ansible.cfg и Pipfile с зависимостями
 +
<spoiler>
 +
[defaults]
 +
#roles_path = /root/ansible/roles:roles
 +
roles_path = ../../roles:roles
 +
#inventory = /root/ansible/inventories/iwad
 +
callback_plugins = /root/ansible/ansible_collection/ansible_collections
 +
interpreter_python = /usr/bin/python3
 +
force_valid_group_names = ignore
 +
host_key_checking = False
 +
stdout_callback = yaml
 +
 +
timeout = 20
 +
config_context = True
 +
fact_caching = jsonfile
 +
fact_caching_connection = inventory/.cache
 +
fact_caching_timeout = 86400
 +
 +
module_defaults:
 +
  ansible.builtin.setup:
 +
    gather_timeout: 10
 +
  ansible.builtin.gather_facts:
 +
    gather_timeout: 10
 +
 +
[ssh_connection]
 +
scp_if_ssh = True
 +
delay=10
 +
retries=2
 +
pipelining=True
 +
ssh_args = -o ControlMaster=auto -o ControlPersist=5m -o ConnectionAttempts=3 -o UserKnownHostsFile=/dev/null
 +
</spoiler>
  
 
Создадим директории и положим конфиги и прочее
 
Создадим директории и положим конфиги и прочее
Строка 27: Строка 57:
  
  
Install the NetBox Ansible Collection.
+
Клонируем репу с базовой ролью
 
 
Before using this collection, you need to install it with the Ansible Galaxy command-line tool
 
ansible-galaxy collection install netbox.netbox
 
 
 
  
Set environment variables for your NetBox API token and URL of your NetBox instance:
+
Создаём виртуальное окружение
  export NETBOX_API=<YOUR_NETBOX_URL> (note - must include http:// or https://)
+
  cd /root/ansible/playbooks/base
  export NETBOX_TOKEN=<YOUR_NETBOX_API_TOKEN>
+
  pipenv install
 +
pipenv shell
  
  
Приводим конфиг примерно к такому виду
+
Приводим <code>/inventories/iwad/netbox-inventory.yaml</code> примерно к такому виду
 
  ---
 
  ---
 
  plugin: netbox.netbox.nb_inventory
 
  plugin: netbox.netbox.nb_inventory

Версия 17:41, 18 марта 2026

Для начала подготовим виртуалочку для управления инфрой через ansible. Использовать будем Debian 12

Ставим python3.11 (т.к. он будет в зависимостях в нашем Pipfile) и pip

apt install python3.11-full
apt install pip


Устанавливаем pipenv

pip install pipenv --break-system-packages


Подготавливаем ansible.cfg и Pipfile с зависимостями Spoiler


Создадим директории и положим конфиги и прочее

/inventories
	/iwad
		/group_vars
			all.yaml
		netbox-inventory.yaml
/playbooks
	/base
		ansible.cfg
		base.yaml
		Pipfile
/roles
	/base


Клонируем репу с базовой ролью

Создаём виртуальное окружение

cd /root/ansible/playbooks/base
pipenv install
pipenv shell


Приводим /inventories/iwad/netbox-inventory.yaml примерно к такому виду

---
plugin: netbox.netbox.nb_inventory
api_endpoint: https://netbox.iwad.ru
token: fc58b84c25grbc5506627a8c32r32a397213ee
validate_certs: false
config_context: false
group_names_raw: True

group_by:
  - device_roles
compose:
  nbx_role: role.name
  primary_ip_address: primary_ip.address
query_filters:
  - status: 'active'
  - cf_device_class: server
  - tenant: org_iwad
device_query_filters:
  - has_primary_ip: 'true'
vm_query_filters:
  - has_primary_ip: 'true'


проверяем что инвентарь парсится(конечно же в netbox уже должны быть внесены устройства)

ansible-inventory -i ../../inventories/iwad --graph
@all:
  |--@ungrouped:
  |--@proxmox:
  |  |--pve36.iwad.ru
  |  |--pve37.iwad.ru
  |  |--pve38.iwad.ru
  |  |--pve42.iwad.ru

или

ansible-inventory -i ../../inventories/iwad --list

кладём id_rsa поьзователю ansible(не умно, признаю) и пробуем катать базовую роль

РАБОТАЕМ!!!


https://netboxlabs.com/docs/integrations/tool-integrations/netbox-ansible-collection/#use-case-1---netbox-as-a-dynamic-inventory-source-for-ansible

https://docs.ansible.com/projects/ansible/latest/collections/netbox/netbox/nb_inventory_inventory.html

https://habr.com/ru/companies/ruvds/articles/962710/

https://demo.netbox.dev/api/schema/swagger-ui/#/