SlideShare a Scribd company logo
Ansible Callback Plugins
Jiri Tyr
About me
● Using Ansible since 2014
● Ansible contributor
○ Modules: yum_repository , jenkins_plugin , ldap_attr, ldap_entry
○ Jinja2 filter: comment
○ Bug fixing (mount module)
○ Code reviews
● Author of more than 100 publicly available Ansible roles
○ https://github.com/jtyr
○ https://galaxy.ansible.com/jtyr
What are callback plugins?
What are callback plugins?
● Control most of the Ansible's output by responding to events
● Over 30 built-in plugins
○ Format output (json, yaml, debug, dense, minimal, unixy, stderr, null, ...)
○ Send output to other system (slack, jabber, mail, grafana_annotations, logstash, splunk, ...)
How to use it?
How to use it?
# Command line
export ANSIBLE_STDOUT_CALLBACK=json
ansible-playbook -i hosts site.yaml
export ANSIBLE_LOAD_CALLBACK_PLUGINS=yes
export ANSIBLE_STDOUT_CALLBACK=json
ansible all -i hosts -m ping
# ansible.cfg
[defaults]
callback_plugins = path/to/my/plugins
Stdout_callback = json
bin_ansible_callbacks = True
How to use it?
# Query variable from Ansible
export ANSIBLE_LOAD_CALLBACK_PLUGINS=yes
export ANSIBLE_STDOUT_CALLBACK=json
export MYHOST=host01
ansible $MYHOST -i hosts -m debug -a 'var=ansible_host' | 
jq ".plays[0].tasks[0].hosts["$MYHOST"].ansible_host" | 
sed -e 's/^"//' -e 's/"$//' -e 's/^null$//'
How does it work?
● Two versions of callback functions
○ Functions for Ansible 2.x prefixed with v2_
● Three categories of callback functions
○ Playbook (playbook, play, task)
○ Runner (module)
○ Other (any, diff)
How does it work?
How does it work?
# Playbook
v2_playbook_on_cleanup_task_start
v2_playbook_on_handler_task_start
v2_playbook_on_import_for_host
v2_playbook_on_include
v2_playbook_on_no_hosts_matched
v2_playbook_on_no_hosts_remaining
v2_playbook_on_notify
v2_playbook_on_not_import_for_host
v2_playbook_on_play_start
v2_playbook_on_start
v2_playbook_on_stats
v2_playbook_on_task_start
v2_playbook_on_vars_prompt
# Runner
v2_runner_item_on_failed
v2_runner_item_on_ok
v2_runner_item_on_skipped
v2_runner_on_async_failed
v2_runner_on_async_ok
v2_runner_on_async_poll
v2_runner_on_failed
v2_runner_on_ok
v2_runner_on_skipped
v2_runner_on_start
v2_runner_on_unreachable
v2_runner_retry
# Other
v2_on_any
v2_on_file_diff
How does it work?
# callback_plugins/mycallback.py
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
CALLBACK_NAME = ' mycallback'
def v2_playbook_on_play_start(self, play):
self._display.display("Starting play")
def v2_playbook_on_stats(self, stats):
self._display.display("Showing stats")
$ ANSIBLE_STDOUT_CALLBACK= mycallback ansible-playbook -i localhost, site.yaml
Starting play
Showing stats
CSV callback plugin
● Allows to use Ansible as a reporting tool
● Turns Ansible's output into CSV (Comma-Separated Values)
● Meant to be used by plays producing output to STDOUT (raw or shell module)
● The output must be either valid CSV format or it has to fail (no empty string)
● Unsuccessful PR #65801
CSV callback plugin
CSV callback plugin
# Default usage
$ export ANSIBLE_CALLBACK_PLUGINS=callback_plugins
$ export ANSIBLE_LOAD_CALLBACK_PLUGINS=1
$ export ANSIBLE_STDOUT_CALLBACK=csv
$ ansible all -i localhost, -c local -m raw -a "echo ','"
host,status
localhost,ok
TOTAL: 1
OK: 1
FAILED: 0
UNREACHABLE: 0
CSV callback plugin
# Customized usage
[callback_csv]
fields = [
{'placeholder': '%n', 'name': 'name'},
{'name': 'host', 'in_message': True},
{'placeholder': '%h', 'name': 'ip', 'in_message': True},
{'name': 'distro', 'in_message': True},
{'name': 'version', 'in_message': True},
{'name': 'cpu', 'in_message': True},
{'name': 'mem', 'in_message': True},
{'placeholder': '%s', 'name': 'status'},
{'placeholder': '%g', 'name': 'group'},
{'placeholder': '%v', 'variable': 'inventory_hostname_short', 'name': 'short'}]
format_ok = %n,%m,%s,%g,%v
CSV callback plugin
# Customized usage
$ export ANSIBLE_CALLBACK_PLUGINS=callback_plugins
$ export ANSIBLE_LOAD_CALLBACK_PLUGINS=1
$ export ANSIBLE_STDOUT_CALLBACK=csv
$ ansible all -i localhost, -c local -m raw 
-a "echo $(cat ./facts.sh | base64 -w0) |
base64 -di > ./facts.sh &&
chmod +x ./facts.sh &&
./facts.sh"
name,hostname,ip,distro,version,cpu,mem,status,group,short
localhost,my.hostname.com,192.168.1.123,centos,7,4,3881048,ok,ungrouped,localhost
TOTAL: 1
OK: 1
FAILED: 0
UNREACHABLE: 0
CSV callback plugin
# Customized usage - Windows
$ export ANSIBLE_CALLBACK_PLUGINS=callback_plugins
$ export ANSIBLE_LOAD_CALLBACK_PLUGINS=1
$ export ANSIBLE_STDOUT_CALLBACK=csv
$ ansible host01 -i hosts -m win_shell -a '$myhost =
[System.Net.Dns]::GetHostByName((hostname)).HostName; $ip = Test-Connection -ComputerName
(hostname) -Count 1 | Select IPV4Address | %{$_.IPV4Address} | %{$_.IPAddressToString};
$version = Get-CimInstance Win32_OperatingSystem | select Version | %{$_.Version}; $cpu =
Get-WmiObject –class Win32_ComputerSystem | select NumberOfProcessors |
%{$_.NumberOfProcessors}; $mem = Get-WmiObject –class Win32_ComputerSystem | select
TotalPhysicalMemory | %{$_.TotalPhysicalMemory}; "{0},{1},windows,{2},{3},{4}" -f
$myhost.ToLower(), $ip, $version, $cpu, [int]($mem/1000)'
name,hostname,ip,distro,version,cpu,mem,status,group,short
host01,my.hostname.com,192.168.1.456,windows,10.0.18363,4,3881048,ok,ungrouped,host01
TOTAL: 1
OK: 1
FAILED: 0
UNREACHABLE: 0
Demo
Thank you for your attention!
Questions?
Ad

More Related Content

What's hot (20)

PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)
PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)
PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)
NTT DATA Technology & Innovation
 
[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode
Akihiro Suda
 
Kafka・Storm・ZooKeeperの認証と認可について #kafkajp
Kafka・Storm・ZooKeeperの認証と認可について #kafkajpKafka・Storm・ZooKeeperの認証と認可について #kafkajp
Kafka・Storm・ZooKeeperの認証と認可について #kafkajp
Yahoo!デベロッパーネットワーク
 
H2O - the optimized HTTP server
H2O - the optimized HTTP serverH2O - the optimized HTTP server
H2O - the optimized HTTP server
Kazuho Oku
 
Embulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loaderEmbulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loader
Sadayuki Furuhashi
 
LLVM Backend の紹介
LLVM Backend の紹介LLVM Backend の紹介
LLVM Backend の紹介
Akira Maruoka
 
分散ワークフローエンジン『Digdag』の実装 at Tokyo RubyKaigi #11
分散ワークフローエンジン『Digdag』の実装 at Tokyo RubyKaigi #11分散ワークフローエンジン『Digdag』の実装 at Tokyo RubyKaigi #11
分散ワークフローエンジン『Digdag』の実装 at Tokyo RubyKaigi #11
Sadayuki Furuhashi
 
インメモリーデータグリッドの選択肢
インメモリーデータグリッドの選択肢インメモリーデータグリッドの選択肢
インメモリーデータグリッドの選択肢
Masaki Yamakawa
 
OpenStackユーザ会資料 - Masakari
OpenStackユーザ会資料 - MasakariOpenStackユーザ会資料 - Masakari
OpenStackユーザ会資料 - Masakari
masahito12
 
[AWSマイスターシリーズ] Instance Store & Elastic Block Store
[AWSマイスターシリーズ] Instance Store & Elastic Block Store[AWSマイスターシリーズ] Instance Store & Elastic Block Store
[AWSマイスターシリーズ] Instance Store & Elastic Block Store
Amazon Web Services Japan
 
Migration to ClickHouse. Practical guide, by Alexander Zaitsev
Migration to ClickHouse. Practical guide, by Alexander ZaitsevMigration to ClickHouse. Practical guide, by Alexander Zaitsev
Migration to ClickHouse. Practical guide, by Alexander Zaitsev
Altinity Ltd
 
Dive into Fluentd plugin v0.12
Dive into Fluentd plugin v0.12Dive into Fluentd plugin v0.12
Dive into Fluentd plugin v0.12
N Masahiro
 
Inside PostgreSQL Shared Memory
Inside PostgreSQL Shared MemoryInside PostgreSQL Shared Memory
Inside PostgreSQL Shared Memory
EDB
 
Under the Hood of a Shard-per-Core Database Architecture
Under the Hood of a Shard-per-Core Database ArchitectureUnder the Hood of a Shard-per-Core Database Architecture
Under the Hood of a Shard-per-Core Database Architecture
ScyllaDB
 
PostgreSQLでスケールアウト
PostgreSQLでスケールアウトPostgreSQLでスケールアウト
PostgreSQLでスケールアウト
Masahiko Sawada
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
channa basava
 
OpenStack超入門シリーズ いまさら聞けないSwiftの使い方
OpenStack超入門シリーズ いまさら聞けないSwiftの使い方OpenStack超入門シリーズ いまさら聞けないSwiftの使い方
OpenStack超入門シリーズ いまさら聞けないSwiftの使い方
Toru Makabe
 
CyberAgent における OSS の CI/CD 基盤開発 myshoes #CICD2021
CyberAgent における OSS の CI/CD 基盤開発 myshoes #CICD2021CyberAgent における OSS の CI/CD 基盤開発 myshoes #CICD2021
CyberAgent における OSS の CI/CD 基盤開発 myshoes #CICD2021
whywaita
 
PostgreSQL Unconference #29 Unicode IVS
PostgreSQL Unconference #29 Unicode IVSPostgreSQL Unconference #29 Unicode IVS
PostgreSQL Unconference #29 Unicode IVS
Noriyoshi Shinoda
 
Ansible Introduction
Ansible Introduction Ansible Introduction
Ansible Introduction
Robert Reiz
 
PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)
PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)
PostgreSQLをKubernetes上で活用するためのOperator紹介!(Cloud Native Database Meetup #3 発表資料)
NTT DATA Technology & Innovation
 
[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode
Akihiro Suda
 
H2O - the optimized HTTP server
H2O - the optimized HTTP serverH2O - the optimized HTTP server
H2O - the optimized HTTP server
Kazuho Oku
 
Embulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loaderEmbulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loader
Sadayuki Furuhashi
 
LLVM Backend の紹介
LLVM Backend の紹介LLVM Backend の紹介
LLVM Backend の紹介
Akira Maruoka
 
分散ワークフローエンジン『Digdag』の実装 at Tokyo RubyKaigi #11
分散ワークフローエンジン『Digdag』の実装 at Tokyo RubyKaigi #11分散ワークフローエンジン『Digdag』の実装 at Tokyo RubyKaigi #11
分散ワークフローエンジン『Digdag』の実装 at Tokyo RubyKaigi #11
Sadayuki Furuhashi
 
インメモリーデータグリッドの選択肢
インメモリーデータグリッドの選択肢インメモリーデータグリッドの選択肢
インメモリーデータグリッドの選択肢
Masaki Yamakawa
 
OpenStackユーザ会資料 - Masakari
OpenStackユーザ会資料 - MasakariOpenStackユーザ会資料 - Masakari
OpenStackユーザ会資料 - Masakari
masahito12
 
[AWSマイスターシリーズ] Instance Store & Elastic Block Store
[AWSマイスターシリーズ] Instance Store & Elastic Block Store[AWSマイスターシリーズ] Instance Store & Elastic Block Store
[AWSマイスターシリーズ] Instance Store & Elastic Block Store
Amazon Web Services Japan
 
Migration to ClickHouse. Practical guide, by Alexander Zaitsev
Migration to ClickHouse. Practical guide, by Alexander ZaitsevMigration to ClickHouse. Practical guide, by Alexander Zaitsev
Migration to ClickHouse. Practical guide, by Alexander Zaitsev
Altinity Ltd
 
Dive into Fluentd plugin v0.12
Dive into Fluentd plugin v0.12Dive into Fluentd plugin v0.12
Dive into Fluentd plugin v0.12
N Masahiro
 
Inside PostgreSQL Shared Memory
Inside PostgreSQL Shared MemoryInside PostgreSQL Shared Memory
Inside PostgreSQL Shared Memory
EDB
 
Under the Hood of a Shard-per-Core Database Architecture
Under the Hood of a Shard-per-Core Database ArchitectureUnder the Hood of a Shard-per-Core Database Architecture
Under the Hood of a Shard-per-Core Database Architecture
ScyllaDB
 
PostgreSQLでスケールアウト
PostgreSQLでスケールアウトPostgreSQLでスケールアウト
PostgreSQLでスケールアウト
Masahiko Sawada
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
channa basava
 
OpenStack超入門シリーズ いまさら聞けないSwiftの使い方
OpenStack超入門シリーズ いまさら聞けないSwiftの使い方OpenStack超入門シリーズ いまさら聞けないSwiftの使い方
OpenStack超入門シリーズ いまさら聞けないSwiftの使い方
Toru Makabe
 
CyberAgent における OSS の CI/CD 基盤開発 myshoes #CICD2021
CyberAgent における OSS の CI/CD 基盤開発 myshoes #CICD2021CyberAgent における OSS の CI/CD 基盤開発 myshoes #CICD2021
CyberAgent における OSS の CI/CD 基盤開発 myshoes #CICD2021
whywaita
 
PostgreSQL Unconference #29 Unicode IVS
PostgreSQL Unconference #29 Unicode IVSPostgreSQL Unconference #29 Unicode IVS
PostgreSQL Unconference #29 Unicode IVS
Noriyoshi Shinoda
 
Ansible Introduction
Ansible Introduction Ansible Introduction
Ansible Introduction
Robert Reiz
 

Similar to Ansible Callback Plugins (20)

Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
Rodolfo Carvalho
 
Sdl Basic
Sdl BasicSdl Basic
Sdl Basic
roberto viola
 
Development of Ansible modules
Development of Ansible modulesDevelopment of Ansible modules
Development of Ansible modules
jtyr
 
Introduction to ansible
Introduction to ansibleIntroduction to ansible
Introduction to ansible
Omid Vahdaty
 
How to Vim - for beginners
How to Vim - for beginnersHow to Vim - for beginners
How to Vim - for beginners
Marcin Rogacki
 
Ansible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife OrchestrationAnsible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife Orchestration
bcoca
 
Kotlin
KotlinKotlin
Kotlin
BoKaiRuan
 
Getting by with just psql
Getting by with just psqlGetting by with just psql
Getting by with just psql
Corey Huinker
 
Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdf
PPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdfPPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdf
PPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdf
ArjayBalberan1
 
Cassandra and materialized views
Cassandra and materialized viewsCassandra and materialized views
Cassandra and materialized views
Grzegorz Duda
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
Nikita Popov
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for Beginners
Arie Bregman
 
The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6
Wim Godden
 
CLI, the other SAPI
CLI, the other SAPICLI, the other SAPI
CLI, the other SAPI
Combell NV
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
Chen Fisher
 
Openstack taskflow 簡介
Openstack taskflow 簡介Openstack taskflow 簡介
Openstack taskflow 簡介
kao kuo-tung
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
Kamil Toman
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
Rodolfo Carvalho
 
Development of Ansible modules
Development of Ansible modulesDevelopment of Ansible modules
Development of Ansible modules
jtyr
 
Introduction to ansible
Introduction to ansibleIntroduction to ansible
Introduction to ansible
Omid Vahdaty
 
How to Vim - for beginners
How to Vim - for beginnersHow to Vim - for beginners
How to Vim - for beginners
Marcin Rogacki
 
Ansible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife OrchestrationAnsible - Swiss Army Knife Orchestration
Ansible - Swiss Army Knife Orchestration
bcoca
 
Getting by with just psql
Getting by with just psqlGetting by with just psql
Getting by with just psql
Corey Huinker
 
PPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdf
PPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdfPPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdf
PPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdf
ArjayBalberan1
 
Cassandra and materialized views
Cassandra and materialized viewsCassandra and materialized views
Cassandra and materialized views
Grzegorz Duda
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
Nikita Popov
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for Beginners
Arie Bregman
 
The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6
Wim Godden
 
CLI, the other SAPI
CLI, the other SAPICLI, the other SAPI
CLI, the other SAPI
Combell NV
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
Chen Fisher
 
Openstack taskflow 簡介
Openstack taskflow 簡介Openstack taskflow 簡介
Openstack taskflow 簡介
kao kuo-tung
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
Kamil Toman
 
Ad

More from jtyr (11)

Managing VMware VMs with Ansible
Managing VMware VMs with AnsibleManaging VMware VMs with Ansible
Managing VMware VMs with Ansible
jtyr
 
How does Ansible's agentless architecture work?
How does Ansible's agentless architecture work?How does Ansible's agentless architecture work?
How does Ansible's agentless architecture work?
jtyr
 
Variable precedence: Where should I put a variable?
Variable precedence: Where should I put a variable?Variable precedence: Where should I put a variable?
Variable precedence: Where should I put a variable?
jtyr
 
Managing multiple environments with Ansible
Managing multiple environments with AnsibleManaging multiple environments with Ansible
Managing multiple environments with Ansible
jtyr
 
Jinja2 filters
Jinja2 filtersJinja2 filters
Jinja2 filters
jtyr
 
Templating in ansible
Templating in ansibleTemplating in ansible
Templating in ansible
jtyr
 
Make the prompt great again
Make the prompt great againMake the prompt great again
Make the prompt great again
jtyr
 
Best practices for ansible roles development
Best practices for ansible roles developmentBest practices for ansible roles development
Best practices for ansible roles development
jtyr
 
Overcoming problems of the standard Ansible inventory file
Overcoming problems of the standard Ansible inventory fileOvercoming problems of the standard Ansible inventory file
Overcoming problems of the standard Ansible inventory file
jtyr
 
Automation and Ansible
Automation and AnsibleAutomation and Ansible
Automation and Ansible
jtyr
 
LEGO IR Controller
LEGO IR ControllerLEGO IR Controller
LEGO IR Controller
jtyr
 
Managing VMware VMs with Ansible
Managing VMware VMs with AnsibleManaging VMware VMs with Ansible
Managing VMware VMs with Ansible
jtyr
 
How does Ansible's agentless architecture work?
How does Ansible's agentless architecture work?How does Ansible's agentless architecture work?
How does Ansible's agentless architecture work?
jtyr
 
Variable precedence: Where should I put a variable?
Variable precedence: Where should I put a variable?Variable precedence: Where should I put a variable?
Variable precedence: Where should I put a variable?
jtyr
 
Managing multiple environments with Ansible
Managing multiple environments with AnsibleManaging multiple environments with Ansible
Managing multiple environments with Ansible
jtyr
 
Jinja2 filters
Jinja2 filtersJinja2 filters
Jinja2 filters
jtyr
 
Templating in ansible
Templating in ansibleTemplating in ansible
Templating in ansible
jtyr
 
Make the prompt great again
Make the prompt great againMake the prompt great again
Make the prompt great again
jtyr
 
Best practices for ansible roles development
Best practices for ansible roles developmentBest practices for ansible roles development
Best practices for ansible roles development
jtyr
 
Overcoming problems of the standard Ansible inventory file
Overcoming problems of the standard Ansible inventory fileOvercoming problems of the standard Ansible inventory file
Overcoming problems of the standard Ansible inventory file
jtyr
 
Automation and Ansible
Automation and AnsibleAutomation and Ansible
Automation and Ansible
jtyr
 
LEGO IR Controller
LEGO IR ControllerLEGO IR Controller
LEGO IR Controller
jtyr
 
Ad

Recently uploaded (20)

Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 

Ansible Callback Plugins

  • 2. About me ● Using Ansible since 2014 ● Ansible contributor ○ Modules: yum_repository , jenkins_plugin , ldap_attr, ldap_entry ○ Jinja2 filter: comment ○ Bug fixing (mount module) ○ Code reviews ● Author of more than 100 publicly available Ansible roles ○ https://github.com/jtyr ○ https://galaxy.ansible.com/jtyr
  • 3. What are callback plugins?
  • 4. What are callback plugins? ● Control most of the Ansible's output by responding to events ● Over 30 built-in plugins ○ Format output (json, yaml, debug, dense, minimal, unixy, stderr, null, ...) ○ Send output to other system (slack, jabber, mail, grafana_annotations, logstash, splunk, ...)
  • 6. How to use it? # Command line export ANSIBLE_STDOUT_CALLBACK=json ansible-playbook -i hosts site.yaml export ANSIBLE_LOAD_CALLBACK_PLUGINS=yes export ANSIBLE_STDOUT_CALLBACK=json ansible all -i hosts -m ping # ansible.cfg [defaults] callback_plugins = path/to/my/plugins Stdout_callback = json bin_ansible_callbacks = True
  • 7. How to use it? # Query variable from Ansible export ANSIBLE_LOAD_CALLBACK_PLUGINS=yes export ANSIBLE_STDOUT_CALLBACK=json export MYHOST=host01 ansible $MYHOST -i hosts -m debug -a 'var=ansible_host' | jq ".plays[0].tasks[0].hosts["$MYHOST"].ansible_host" | sed -e 's/^"//' -e 's/"$//' -e 's/^null$//'
  • 8. How does it work?
  • 9. ● Two versions of callback functions ○ Functions for Ansible 2.x prefixed with v2_ ● Three categories of callback functions ○ Playbook (playbook, play, task) ○ Runner (module) ○ Other (any, diff) How does it work?
  • 10. How does it work? # Playbook v2_playbook_on_cleanup_task_start v2_playbook_on_handler_task_start v2_playbook_on_import_for_host v2_playbook_on_include v2_playbook_on_no_hosts_matched v2_playbook_on_no_hosts_remaining v2_playbook_on_notify v2_playbook_on_not_import_for_host v2_playbook_on_play_start v2_playbook_on_start v2_playbook_on_stats v2_playbook_on_task_start v2_playbook_on_vars_prompt # Runner v2_runner_item_on_failed v2_runner_item_on_ok v2_runner_item_on_skipped v2_runner_on_async_failed v2_runner_on_async_ok v2_runner_on_async_poll v2_runner_on_failed v2_runner_on_ok v2_runner_on_skipped v2_runner_on_start v2_runner_on_unreachable v2_runner_retry # Other v2_on_any v2_on_file_diff
  • 11. How does it work? # callback_plugins/mycallback.py from ansible.plugins.callback import CallbackBase class CallbackModule(CallbackBase): CALLBACK_VERSION = 2.0 CALLBACK_TYPE = 'stdout' CALLBACK_NAME = ' mycallback' def v2_playbook_on_play_start(self, play): self._display.display("Starting play") def v2_playbook_on_stats(self, stats): self._display.display("Showing stats") $ ANSIBLE_STDOUT_CALLBACK= mycallback ansible-playbook -i localhost, site.yaml Starting play Showing stats
  • 13. ● Allows to use Ansible as a reporting tool ● Turns Ansible's output into CSV (Comma-Separated Values) ● Meant to be used by plays producing output to STDOUT (raw or shell module) ● The output must be either valid CSV format or it has to fail (no empty string) ● Unsuccessful PR #65801 CSV callback plugin
  • 14. CSV callback plugin # Default usage $ export ANSIBLE_CALLBACK_PLUGINS=callback_plugins $ export ANSIBLE_LOAD_CALLBACK_PLUGINS=1 $ export ANSIBLE_STDOUT_CALLBACK=csv $ ansible all -i localhost, -c local -m raw -a "echo ','" host,status localhost,ok TOTAL: 1 OK: 1 FAILED: 0 UNREACHABLE: 0
  • 15. CSV callback plugin # Customized usage [callback_csv] fields = [ {'placeholder': '%n', 'name': 'name'}, {'name': 'host', 'in_message': True}, {'placeholder': '%h', 'name': 'ip', 'in_message': True}, {'name': 'distro', 'in_message': True}, {'name': 'version', 'in_message': True}, {'name': 'cpu', 'in_message': True}, {'name': 'mem', 'in_message': True}, {'placeholder': '%s', 'name': 'status'}, {'placeholder': '%g', 'name': 'group'}, {'placeholder': '%v', 'variable': 'inventory_hostname_short', 'name': 'short'}] format_ok = %n,%m,%s,%g,%v
  • 16. CSV callback plugin # Customized usage $ export ANSIBLE_CALLBACK_PLUGINS=callback_plugins $ export ANSIBLE_LOAD_CALLBACK_PLUGINS=1 $ export ANSIBLE_STDOUT_CALLBACK=csv $ ansible all -i localhost, -c local -m raw -a "echo $(cat ./facts.sh | base64 -w0) | base64 -di > ./facts.sh && chmod +x ./facts.sh && ./facts.sh" name,hostname,ip,distro,version,cpu,mem,status,group,short localhost,my.hostname.com,192.168.1.123,centos,7,4,3881048,ok,ungrouped,localhost TOTAL: 1 OK: 1 FAILED: 0 UNREACHABLE: 0
  • 17. CSV callback plugin # Customized usage - Windows $ export ANSIBLE_CALLBACK_PLUGINS=callback_plugins $ export ANSIBLE_LOAD_CALLBACK_PLUGINS=1 $ export ANSIBLE_STDOUT_CALLBACK=csv $ ansible host01 -i hosts -m win_shell -a '$myhost = [System.Net.Dns]::GetHostByName((hostname)).HostName; $ip = Test-Connection -ComputerName (hostname) -Count 1 | Select IPV4Address | %{$_.IPV4Address} | %{$_.IPAddressToString}; $version = Get-CimInstance Win32_OperatingSystem | select Version | %{$_.Version}; $cpu = Get-WmiObject –class Win32_ComputerSystem | select NumberOfProcessors | %{$_.NumberOfProcessors}; $mem = Get-WmiObject –class Win32_ComputerSystem | select TotalPhysicalMemory | %{$_.TotalPhysicalMemory}; "{0},{1},windows,{2},{3},{4}" -f $myhost.ToLower(), $ip, $version, $cpu, [int]($mem/1000)' name,hostname,ip,distro,version,cpu,mem,status,group,short host01,my.hostname.com,192.168.1.456,windows,10.0.18363,4,3881048,ok,ungrouped,host01 TOTAL: 1 OK: 1 FAILED: 0 UNREACHABLE: 0
  • 18. Demo
  • 19. Thank you for your attention! Questions?