This repo holds custom callback plugin, so your Ansible could write everything in the PostgreSQL database.

Overview

English

What is it?

This is callback plugin that dumps most of the Ansible internal state to the external PostgreSQL database.

What is this for?

If you ever had to:

  • know the value of the certain variable before the role or task starts;
  • implement an audit soultion which should send data to some remote storage for unchangeability;
  • investigate into some Ansible function while dreaming of looking under the hood

...then this plugin is right for you.

Requirements

  • CentOS/RHEL 7.x;
  • Ansible 2.9.x;
  • Python >=3.6.x;
  • PostgreSQL >=10.x (this was debugged with Postgres 12, though)

Quick start guide

  1. Copy to your project directory:
    1. playbooks/callback_plugins/logdb.py
    2. playbooks/module_utils/pg8000/*
    3. playbooks/module_utils/scramp/*
  2. Add settings to the ansible.cfg as follows:
[defaults]
stdout_callback = log2db
callable_plugins = log2db
callback_whitelist = log2db

[log2db_callback]
host = <your PostgreSQL server hostname>
port = <your PostgreSQL server port, usually 5432>
user = <database account with insert privilege>
pass = <database account password>
db = <database name, default is "ansible">
table = <table name, default is "logs">
  1. Do not forget to setup a database and a table before the first launch. Also, an account with proper rights is a must:
[user@hostname]> sudo -u postgres psql
postgres=# CREATE DATABASE <my_db_name> WITH OWNER postgres;
postgres=# CREATE USER <my_db_user>;
postgres=# GRANT CONNECT, CREATE, TEMPORARY ON DATABASE <my_db_name> to <my_db_user>;
postgres=# CREATE TABLE IF NOT EXISTS <my_table_name> (
   uuid uuid not null,
   data jsonb,
   timestamp timestamp with time zone,
   id bigserial
   constraint logs_pk
   primary key,
   origin text);
postgres=# ALTER TABLE <my_table_name> OWNER to <my_db_account>;
postgres=# CREATE INDEX IF NOT EXISTS <my_table_name>_uuid_index on <my_table_name> (uuid);
postgres=# ALTER USER <my_db_user> WITH PASSWORD '<my_db_password>';

How to send a donation to the author

If you want to thank the author - this is a donate link. Any sum is happily accepted.

Legal information

This project is conceived and performed by me, Sergey Pechenko, on my own will, out of working hours, using own hardware.

Copyright: (С) 2021, Sergey Pechenko

Based on "default.py" callback plugin for Ansible, which has own copyrights:

(C) 2012-2014, Michael DeHaan [email protected]

(C) 2017 Ansible Project

This project uses MIT-licensed components as follows:

  • pg8000 (c) 2007-2009, Mathieu Fenniak

  • scramp (C) 2019 Tony Locke

Portions for these components that provide possibility for Ansible to load and run them are also (C) 2021, Sergey Pechenko.

License

GPLv3+ (please see LICENSE)

Contact

You can ask your questions about this plugin at the Ansible chat, or PM me

Русский

Что это?

Коллбэк-плагин для Ansible, который позволяет сохранять бОльшую часть внутренних данных Ansible во внешнюю БД.

Зачем это?

Если тебе когда-нибудь:

  • требовалось при отладке знать значение конкретной переменной перед исполнением таска или вызовом роли;
  • приходилось организовывать аудит с сохранением данных в отдельном от Ansible внешнем хранилище;
  • случалось разбираться с какой-то функций Ansible в мечтах о возможности "заглянуть под капот" -

...то этот плагин - для тебя.

Что требуется?

  • CentOS/RHEL 7.x;
  • Ansible 2.9.x;
  • Python >=3.6.x;
  • PostgreSQL >=10 (отлаживалось на 12);

Как запустить?

  1. Скопируй в каталог с проектом:
    1. playbooks/callback_plugins/logdb.py
    2. playbooks/module_utils/pg8000/*
    3. playbooks/module_utils/scramp/*
  2. Укажи в ansible.cfg следующее:
[defaults]
stdout_callback = logdb
callable_plugins = logdb
callback_whitelist = logdb

[logdb_callback]
host = <имя хоста PostgreSQL>
port = <порт сервера PostgreSQL, обычно 5432>
user = <учётная запись в БД с правами на INSERT>
pass = <пароль этой учётной записи>
db = <название БД, по умолчанию "ansible">
table = <название таблицы, по умолчанию "logs">
  1. Перед запуском не забудь создать БД и таблицу. А ещё понадобится создать учётку и дать ей права:
[user@hostname]> sudo -u postgres psql
postgres=# CREATE DATABASE <название БД> WITH OWNER postgres;
postgres=# CREATE USER <учётная запись>;
postgres=# GRANT CONNECT, CREATE, TEMPORARY ON DATABASE <название БД> to <учётная запись>;
postgres=# CREATE TABLE IF NOT EXISTS <название таблицы> (
   uuid uuid not null,
   data jsonb,
   timestamp timestamp with time zone,
   id bigserial
   constraint logs_pk
   primary key,
   origin text);
postgres=# ALTER TABLE <название таблицы> OWNER to <учётная запись>;
postgres=# CREATE INDEX IF NOT EXISTS <название таблицы>_uuid_index on <название таблицы> (uuid);
postgres=# ALTER USER <учётная запись> WITH PASSWORD '<пароль учётной записи>';

Поблагодарить автора

Если хочешь поблагодарить автора - вот ссылка для донатов. Буду рад любой сумме.

Правовая информация

Этот проект задуман и выполнен мною, Сергеем Печенко, по личной инициативе в нерабочее время на личном оборудовании.

Авторские права: (С) 2021, Sergey Pechenko

Проект выполнен на основе коллбэк-плагина "default.py" для Ansible. Авторские права на оригинальный файл:

(C) 2012-2014, Michael DeHaan [email protected]

(C) 2017 Ansible Project

При создании проекта по лицензии MIT использованы следующие компоненты:

  • pg8000 (C) Mathieu Fenniak
  • scramp (C) Tony Locke

Авторские права на части этих компонентов, обеспечивающие Ansible возможность их загрузки и выполнения: (С) 2021, Сергей Печенко

Лицензия

GPLv3+

Контакты

Можешь задать свои вопросы в чате по Ansible, или написать мне в ЛС.

You might also like...
Write complicated anonymous functions other than lambdas in Python.

lambdex allows you to write multi-line anonymous function expression (called a lambdex) in an idiomatic manner.

My sister is a GR of her class. She had to mark attendance of students from screenshots of teams meeting on an excel sheet. I resolved her problem by reading names from screenshots using PyTesseract and marking them present on the excel using Pandas in Python. It took me 1hr to write the code and it is saving half an hour everyday. sawa (ꦱꦮ) is an open source programming language, an interpreter to be precise, where you can write python code using javanese character.
sawa (ꦱꦮ) is an open source programming language, an interpreter to be precise, where you can write python code using javanese character.

ꦱꦮ sawa (ꦱꦮ) is an open source programming language, an interpreter to be precise, where you can write python code using javanese character. sawa iku

This is a modified variation of abhiTronix's vidgear. In this variation, it is possible to write the output file anywhere regardless the permissions.
This is a modified variation of abhiTronix's vidgear. In this variation, it is possible to write the output file anywhere regardless the permissions.

Info In order to download this package: Windows 10: Press Windows+S, Type PowerShell (cmd in older versions) and hit enter, Type pip install vidgear_n

Why write code when you can import it directly from GitHub Copilot?

Copilot Importer Why write code when you can import it directly from GitHub Copilot? What is Copilot Importer? The copilot python module will dynamica

An extension for Arma 3 that lets you write extensions in Python 3
An extension for Arma 3 that lets you write extensions in Python 3

An Arma 3 extension that lets you to write python extensions for Arma 3. And it's really simple and straightforward to use!

Generate Openbox Menus from a easy to write configuration file.

openbox-menu-generator Generate Openbox Menus from a easy to write configuration file. Example Configuration: ('#' indicate comments but not implement

 A simple way to read and write LAPS passwords from linux.
A simple way to read and write LAPS passwords from linux.

A simple way to read and write LAPS passwords from linux. This script is a python setter/getter for property ms-Mcs-AdmPwd used by LAPS inspired by @s

Write a program that works out whether if a given year is a leap year
Write a program that works out whether if a given year is a leap year

Leap Year 💪 This is a Difficult Challenge 💪 Instructions Write a program that works out whether if a given year is a leap year. A normal year has 36

Comments
  • Similarities with ara and opportunities for collaboration

    Similarities with ara and opportunities for collaboration

    Hi o/

    I saw your comment about this project in https://github.com/ansible/community/issues/546#issuecomment-945181857 but since it's not an issue meant for discussions I thought I could create an issue here instead.

    I was wondering if you knew about ara: https://github.com/ansible-community/ara ? It leverages a callback for saving the execution results to sqlite, mysql and postgresql and then provides an API for querying results.

    There's a live demo here: https://demo.recordsansible.org/ (API: https://demo.recordsansible.org/api/v1/)

    I thought that perhaps there might be an opportunity to collaborate ?

    Let me know !

    opened by dmsimard 1
Owner
Sergey Pechenko
Sergey Pechenko
Script to check if your Bistromatic handle everything as it should.

Bistromatic Checker Script to check if your Bistromatic handle everything as it should. The bistromatic is the project marking the end of the CPool at

Mathias 1 Dec 27, 2021
One Ansible Module for using LINE notify API to send notification. It can be required in the collection list.

Ansible Collection - hazel_shen.line_notify Documentation for the collection. ansible-galaxy collection install hazel_shen.line_notify --ignore-certs

Hazel Shen 4 Jul 19, 2021
ARA Records Ansible and makes it easier to understand and troubleshoot.

ARA Records Ansible ARA Records Ansible and makes it easier to understand and troubleshoot. It's another recursive acronym. What it does Simple to ins

Community managed Ansible repositories 1.6k Dec 25, 2022
a sketch of what a zkvm could look like

We want to build a ZKP that validates an entire EVM block or as much of it as we can efficiently. Its okay to adjust the gas costs for every EVM opcode. Its also to exclude some opcodes for now if they are super expensive. Its okay to exclude precompiles.

null 25 Dec 30, 2022
Enhanced version of blender's bvh add-on with more settings supported. The bvh's rest pose should have the same handedness as the armature while could use a different up/forward definiton.

Enhanced bvh add-on (importer/exporter) for blender Enhanced bvh add-on (importer/exporter) for blender Enhanced bvh importer Enhanced bvh exporter Ho

James Zhao 16 Dec 20, 2022
Custom Weapons 3 attribute support for Custom Weapons X

CW3toX Allows use of Custom Weapons 3 attributes in Custom Weapons X. Requiremen

null 2 Mar 1, 2022
Fabric mod where anyone can PR anything, concerning or not. I'll merge everything as soon as it works.

Guess What Will Happen In This Fabric mod where anyone can PR anything, concerning or not (Unless it's too concerning). I'll merge everything as soon

anatom 65 Dec 25, 2022
This is a Poetry plugin that will make it possible to build projects using custom TOML files

Poetry Multiproject Plugin This is a Poetry plugin that will make it possible to build projects using custom TOML files. This is especially useful whe

David Vujic 69 Dec 25, 2022
IDA Pro plugin that shows the comments in a database

ShowComments A Simple IDA Pro plugin that shows the comments in a database Installation Copy the file showcomments.py to the plugins folder under IDA

Fernando Mercês 32 Dec 10, 2022
Repo Home WPDrawBot - (Repo, Home, WP) A powerful programmatic 2D drawing application for MacOS X which generates graphics from Python scripts. (graphics, dev, mac)

DrawBot DrawBot is a powerful, free application for macOS that invites you to write Python scripts to generate two-dimensional graphics. The built-in

Frederik Berlaen 342 Dec 27, 2022