AWX. Getting a dynamic list of hosts from Zabbix and putting it into the AWX inventory
Links
Tasks
- Creating Gitlab repo
- Creating custom image awx-ee-custom (Execution Environment), containing python-module zabbix-api (standard awx-ee image doesn't have it). This image is required for getting a dynamic list of hosts from Zabbix (using python-script)
- Creating Project AWX
- Creating Inventory AWX
Requirements
- Gitlab at own server (Installation: Gitlab. Almalinux 8. Install)
- Docker Registry at own server (Installation: Docker. Docker Registry Server (own Docker Hub to store images))
- AWX 21.x.x on Docker (Installation: AWX. AlmaLinux 8. Install AWX with Docker containers):
- Docker installed and running locally (Installation: Docker. Install)
- python3 installed ( 3.9.2 ) (Installation: Python. Install)
Installation
Gitlab server
Creating repo "awx" at own Gitlab server using similar tree of directories and files:
awx/ ├── inventory/ └── zabbix.py
Script zabbix.py (for getting list of hosts):
You have to edit following variables: self.zabbix_server, self.zabbix_username, self.zabbix_password
#!/usr/bin/env python
# (c) 2013, Greg Buehler
# (c) 2018, Filippo Ferrazini
#
# This file is part of Ansible,
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
######################################################################
"""
Zabbix Server external inventory script.
========================================
Returns hosts and hostgroups from Zabbix Server.
If you want to run with --limit against a host group with space in the
name, use asterisk. For example --limit="Linux*servers".
Configuration is read from `zabbix.ini`.
Tested with Zabbix Server 2.0.6, 3.2.3 and 3.4.
"""
from __future__ import print_function
import os
import sys
import argparse
from ansible.module_utils.six.moves import configparser
try:
from zabbix_api import ZabbixAPI
except Exception:
print("Error: Zabbix API library must be installed: pip install zabbix-api.",
file=sys.stderr)
sys.exit(1)
import json
class ZabbixInventory(object):
def read_settings(self):
config = configparser.SafeConfigParser()
# conf_path = './zabbix.ini'
conf_path = '/var/lib/awx/projects/Alefstudio/inventory/zabbix.ini'
if not os.path.exists(conf_path):
conf_path = os.path.dirname(os.path.realpath(__file__)) + '/zabbix.ini'
if os.path.exists(conf_path):
config.read(conf_path)
# server
self.zabbix_server = "http://192.168.1.111/zabbix"
# login
self.zabbix_username = "admin"
self.zabbix_password = "PassWord"
# ssl certs
self.validate_certs = False
# host inventory
self.read_host_inventory = True
# host interface
self.use_host_interface = True
def read_cli(self):
parser = argparse.ArgumentParser()
parser.add_argument('--host')
parser.add_argument('--list', action='store_true')
self.options = parser.parse_args()
def hoststub(self):
return {
'hosts': []
}
def get_host(self, api, name):
api_query = {'output': 'extend', 'selectGroups': 'extend', "filter": {"host": [name]}}
if self.use_host_interface:
api_query['selectInterfaces'] = ['useip', 'ip', 'dns']
if self.read_host_inventory:
api_query['selectInventory'] = "extend"
data = {'ansible_ssh_host': name}
if self.use_host_interface or self.read_host_inventory:
try:
hosts_data = api.host.get(api_query)[0]
if 'interfaces' in hosts_data:
# use first interface only
if hosts_data['interfaces'][0]['useip'] == 0:
data['ansible_ssh_host'] = hosts_data['interfaces'][0]['dns']
else:
data['ansible_ssh_host'] = hosts_data['interfaces'][0]['ip']
if ('inventory' in hosts_data) and (hosts_data['inventory']):
data.update(hosts_data['inventory'])
except IndexError:
# Host not found in zabbix
pass
return data
def get_list(self, api):
api_query = {'output': 'extend', 'selectGroups': 'extend'}
if self.use_host_interface:
api_query['selectInterfaces'] = ['useip', 'ip', 'dns']
if self.read_host_inventory:
api_query['selectInventory'] = "extend"
hosts_data = api.host.get(api_query)
data = {'_meta': {'hostvars': {}}}
data[self.defaultgroup] = self.hoststub()
for host in hosts_data:
hostname = host['name']
hostvars = dict()
data[self.defaultgroup]['hosts'].append(hostname)
for group in host['groups']:
groupname = group['name']
if groupname not in data:
data[groupname] = self.hoststub()
data[groupname]['hosts'].append(hostname)
if 'interfaces' in host:
# use first interface only
if host['interfaces'][0]['useip'] == 0:
hostvars['ansible_ssh_host'] = host['interfaces'][0]['dns']
else:
hostvars['ansible_ssh_host'] = host['interfaces'][0]['ip']
if ('inventory' in host) and (host['inventory']):
hostvars.update(host['inventory'])
data['_meta']['hostvars'][hostname] = hostvars
return data
def __init__(self):
self.defaultgroup = 'group_all'
self.zabbix_server = None
self.zabbix_username = None
self.zabbix_password = None
self.validate_certs = True
self.read_host_inventory = False
self.use_host_interface = True
self.meta = {}
self.read_settings()
self.read_cli()
if self.zabbix_server and self.zabbix_username:
try:
api = ZabbixAPI(server=self.zabbix_server, validate_certs=self.validate_certs)
api.login(user=self.zabbix_username, password=self.zabbix_password)
# zabbix_api tries to exit if it cannot parse what the zabbix server returned
# so we have to use SystemExit here
except (Exception, SystemExit) as e:
print("Error: Could not login to Zabbix server. Check your zabbix.ini.", file=sys.stderr)
sys.exit(1)
if self.options.host:
data = self.get_host(api, self.options.host)
print(json.dumps(data, indent=2))
elif self.options.list:
data = self.get_list(api)
print(json.dumps(data, indent=2))
else:
print("usage: --list ..OR.. --host <hostname>", file=sys.stderr)
sys.exit(1)
else:
print("Error: Configuration of server and credentials are required. See zabbix.ini.", file=sys.stderr)
sys.exit(1)
ZabbixInventory()
AWX Server
Generate SSH key at AWX and add it to Gitlab via web-interface
It's neccessary if you have to work with Gitlab repo at different host
ssh-keygen
- You will get two keys in ~/.ssh/ (/root/.ssh/) directory:
- "id_rsa" would be your private key
- "id_rsa.pub" would be your public key.
- Add content of /root/.ssh/id_rsa.pub at Gitlab web-interface in user Profile:
User settings - SSH key - Next we can clone Gitlab repo at AWX host. For example:
git clone git@192.168.199.160:gitlab-instance-8aac966e/awx.git
It's neccessary to have our script zabbix.py at Gitlab executable
Otherwise it won't be appear after running dynamic inventory
To do it clone repo to AWX host
mkdir ~/git_projects
cd ~/git_projects
git clone git@192.168.199.160:gitlab-instance-8aac966e/awx.git
cd ~/awx
Prepare files and push it back to Gitlab
chmod +x inventory/zabbix.py
git add inventory/zabbix.py
git config --global user.name "Cless"
git config --global user.email "clesssalvein@gmail.com"
git commit -m "sync to gitlab zabbix.py"
git push origin
Now script zabbix.py after Project syn will appear in AWX Inventory and we can choose it for running
Custom awx-ee image creating
Create a new clean python venv
mkdir ~/ansible-builder && cd ~/ansible-builder
python3.9 -m venv builder
source builder/bin/activate
Install the components:
pip install ansible
pip install ansible-builder==1.0.0.0a1
Create the config
Pay attention to the string: "- RUN pip3 install zabbix-api ; pip3 install ansible". It's neccessary to make zabbix-api work.
nano execution-environment.yml
version: 1
dependencies:
galaxy: requirements.yml
python: requirements.txt
system: bindep.txt
additional_build_steps:
append:
- RUN alternatives --set python /usr/bin/python3
- RUN pip3 install zabbix-api ; pip3 install ansible
- COPY --from=quay.io/project-receptor/receptor:0.9.7 /usr/bin/receptor /usr/bin/receptor
- RUN mkdir -p /var/run/receptor
- ADD run.sh /run.sh
- CMD /run.sh
- USER 1000
- RUN git lfs install
nano requirements.yml
---
collections:
- community.general
nano requirements.txt
urllib3
git+https://github.com/ansible/ansible-builder.git@devel#egg=ansible-buildernano bindep.txt
python38-devel [platform:rpm compile]
subversion [platform:rpm]
subversion [platform:dpkg]
git-lfs [platform:rpm]Create dir
mkdir context
nano context/run.sh
#! /bin/bash
ansible-runner worker --private-data-dir=/runner
Add executable perms to script
chmod +x context/run.sh
Build the EE Image
ansible-builder build --tag registry.domain123.ru:5000/awx-custom-ee:latest --context ./context --container-runtime docker
... Running command: docker build -f ./context/Dockerfile -t registry.domain123.ru:5000 ./context Running command: docker run --rm -v /Users/pgriffit/ansible-builder/builder/lib/python3.9/site-packages/ansible_builder:/ansible_builder_mount:Z registry.domain123.ru:5000:latest python3 /ansible_builder_moun/introspect.py Running command: docker build -f ./context/Dockerfile -t registry.domain123.ru:5000 ./context Complete! The build context can be found at: /Users/pgriffit/ansible-builder/context ...
We should now have a container image
docker images
... registry.domain123.ru:5000/awx-custom-ee latest 4a9eba58d909 2 hours ago 1.44GB ...
Login Registry
docker login registry.domain123.ru:5000
Login: xxx Password: xxx
Push image to Registry
docker push registry.domain123.ru:5000/awx-custom-ee:latest
Docker Registry credentials creating
Credentials - Add
Name: registry.domain123.ru:5000
Credential Type: Container Registry
Authentication URL: registry.domain123.ru:5000
User: admin
Password: xxx
Execution Environments creating
Execution Environments - Add
Name: awx-custom-ee
Image: registry.domain123.ru:5000/awx-custom-ee:latest
Pull: Always
Registry credential: registry.domain123.ru:5000
Credentials SCM (Gitlab) creating
Credentials - Add
Name: gitlab
Credential Type: Source control
SCM Private Key: <...> # At this host (AWX) create SSH key (we've already created it above): "ssh-keygen". Put content of file /root/.ssh/id_rsa into this field. At Gitlab in user Profile add new SSH-key, and put content of /root/.ssh/id_rsa.pub there
AWX Project creating
Project - Add
Name: awx-zabbix-host-control
SCM type: Git
Source Control Credential: Scm: gitlab
Source Control URL: git@192.168.199.160:gitlab-instance-8aac966e/awx.git
Default Execution Environment: awx-custom-ee
Clean: V
Update revision on launch: V
Inventory creating
Inventories - awx - Sources - awx - Edit
Name: test
Execution Environment: awx-custom-ee
Source: test
Inventory file: inventory/zabbix.py
Update options: Overwrite
Now you can run Inventories - awx - Sources - awx - Launch
After that, the hosts and groups should appear in the inventory