SlideShare a Scribd company logo
1 of 45
Download to read offline
Writing Ansible Modules
Martin Schütte
11 November 2019
Assumptions
You …
• configure servers or network devices
• have already seen Ansible config
• can write shell scripts
This talk …
• is no Ansible how-to
• has more slides online
• is available on noti.st
Martin Schütte | Ansible Modules | DENOG 11 2/34
Outline
1. Concepts
Module Basics
Orchestration with Host Delegation
2. Writing Modules
Simple Example: ipify API
Patterns & Misc. Hints
Debugging
Beyond Python
3. Conclusion
Martin Schütte | Ansible Modules | DENOG 11 3/34
Concepts
Concepts
Intro
Ansible – Concepts and Naming
Ansible is a radically simple IT automation platform.
• controller
• target host
• playbook
• role
• task
• module
Martin Schütte | Ansible Modules | DENOG 11 4/34
Example: Simple Playbook
---
- hosts: webserver
vars:
apache_version: latest
tasks:
- name: ensure apache is at given version
yum:
name: httpd
state: ”{{ apache_version }}”
- hosts: dbserver
roles:
- ansible-role-postgresql
Martin Schütte | Ansible Modules | DENOG 11 5/34
Concepts
Module Basics
What is a Module?
some code snippet to run on the (remote) host
executable with input and output
Martin Schütte | Ansible Modules | DENOG 11 6/34
Minimal Module
#!/bin/sh
echo '{”foo”: ”bar”}'
exit 0
#!/usr/bin/python
if __name__ == '__main__':
print('{”foo”: ”bar”}')
exit(0)
Martin Schütte | Ansible Modules | DENOG 11 7/34
Action Plugins call Modules
• plugins run on the controller
• may prepare input for modules
• may handle “special” connections (non SSH or WinRM)
• defaults to normal to run module on target host
Martin Schütte | Ansible Modules | DENOG 11 8/34
Concepts
Orchestration with Host Delegation
normal SSH Target
# in Playbook
- hosts: webserver
tasks:
- name: webserver reload
service:
name: httpd
state: reloaded
Martin Schütte | Ansible Modules | DENOG 11 9/34
normal SSH Target, with delegate_to
- hosts: webserver
tasks:
- name: webserver reload
# ...
- name: loadbalancer reload
delegate_to: loadbalancer
service:
name: nginx
state: reloaded
Martin Schütte | Ansible Modules | DENOG 11 10/34
Network, Vendor Specific junos_command
- hosts: router
tasks:
- name: get interfaces
connection: local
junos_command:
command: show interface terse
provider:
host: router
username: foo
Martin Schütte | Ansible Modules | DENOG 11 11/34
Network, New Generic cli_command
- hosts: router
tasks:
- name: get interfaces
cli_command:
command: show interface terse
# uses Ansible inventory to read variables
# ansible_network_os=junos, ansible_connection=network_cli,
# ansible_user, ansible_password, ansible_ssh_common_args
Martin Schütte | Ansible Modules | DENOG 11 12/34
Writing Modules
Writing Modules
Don’t
Avoid Writing Own Code
• get_url – Downloads files
• uri – Interacts with webservices
• wait_for – Waits for a condition before continuing
• set_fact – Set host facts from a task
- name: Wait for port 8000 to become open on the host
wait_for:
port: 8000
delay: 10
- name: wait for service to become available
uri:
url: 'https://{{ inventory_hostname }}:{{ svc_port }}/service'
return_content: yes
register: content
until: content.status == 200
retries: 60
delay: 10
when: not ansible_check_mode
Martin Schütte | Ansible Modules | DENOG 11 13/34
Writing Modules
Simple Example: ipify API
Documentation
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: ipify_facts
short_description: Retrieve the public IP of your internet gateway
version_added: '2.0'
options:
api_url: ...
'''
EXAMPLES = r'''
# Gather IP facts from ipify.org
- name: Get my public IP
ipify_facts:
# Gather IP facts from your own ipify service endpoint with a custom timeout
- name: Get my public IP
ipify_facts:
api_url: http://api.example.com/ipify
timeout: 20
'''
RETURN = ...
Martin Schütte | Ansible Modules | DENOG 11 14/34
ansible-doc
$ ansible-doc --snippet ipify_facts
- name: Retrieve the public IP of your internet gateway
ipify_facts:
api_url: # URL of the ipify.org API service.
timeout: # HTTP connection timeout in seconds.
validate_certs: # When set to `NO', SSL certificates will not be validated.
$ ansible-doc ipify_facts
> IPIFY_FACTS (.../site-packages/ansible/modules/net_tools/ipify_facts.py)
If behind NAT and need to know the public IP of your internet gateway.
* This module is maintained by The Ansible Community
OPTIONS (= is mandatory):
- api_url
URL of the ipify.org API service.
`?format=json' will be appended per default.
[Default: https://api.ipify.org/]
type: str
...
Martin Schütte | Ansible Modules | DENOG 11 15/34
ipify_facts.py
def main():
global module
module = AnsibleModule(
argument_spec=dict(
api_url=dict(type='str',
default='https://api.ipify.org/'),
timeout=dict(type='int', default=10),
validate_certs=dict(type='bool', default=True),
),
supports_check_mode=True,
)
ipify_facts = IpifyFacts().run()
ipify_facts_result = dict(changed=False,
ansible_facts=ipify_facts)
module.exit_json(**ipify_facts_result)
if __name__ == '__main__':
main()
Martin Schütte | Ansible Modules | DENOG 11 16/34
ipify_facts.py
class IpifyFacts(object):
def __init__(self):
self.api_url = module.params.get('api_url')
self.timeout = module.params.get('timeout')
def run(self):
result = {
'ipify_public_ip': None
}
(response, info) = fetch_url(module=module,
url=self.api_url + ”?format=json”,
force=True, timeout=self.timeout)
if not response:
module.fail_json(msg=”No valid or no response ...”)
data = json.loads(to_text(response.read()))
result['ipify_public_ip'] = data.get('ip')
return result
Martin Schütte | Ansible Modules | DENOG 11 17/34
Usage in Tasks
- name: get IP from alternative service endpoint
ipify_facts:
api_url: https://api6.ipify.org
register: ip_public
- name: debug output
debug:
msg: |
fact: {{ ipify_public_ip }}
reg: {{ ip_public.ansible_facts.ipify_public_ip }}
TASK [my_role : debug output] **********************
ok: [server] => {
”msg”: ”fact: 2001:db8:1:2::42nreg: 2001:db8:1:2::42n”
}
Martin Schütte | Ansible Modules | DENOG 11 18/34
Writing Modules
Patterns & Misc. Hints
my_module.py
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict( # ...
)
)
rc = do_something()
result = {
”msg”: ”Hello World”,
”rc”: rc,
”failed”: False,
”changed”: False,
}
module.exit_json(**result)
if __name__ == '__main__':
main()
Martin Schütte | Ansible Modules | DENOG 11 19/34
File Locations: library and module_utils
my_role/
meta
defaults
tasks
library
my_module.py
module_utils
my_util_lib.py
• role can use Ansible module my_module in tasks
• import * from my_util_lib
finds Python module in module_utils
• for “larger” libraries use packages (pip/rpm/dpkg)
Martin Schütte | Ansible Modules | DENOG 11 20/34
“standard library” AnsibleModule
Useful common methods:
• argument_spec for parameters
• supports_check_mode
• exit_json(), fail_json()
• atomic_move(), run_command()
• bytes_to_human(), human_to_bytes()
Other module_utils:
• api: function/decorator @rate_limit()
• timeout: function/decorator @timeout(secs)
Martin Schütte | Ansible Modules | DENOG 11 21/34
Pattern: Idempotency
• Playbooks can run many times
• As few changes as possible
• Only perform required actions
1. Get spec parameters
2. Check actual state of system
if = then: done, do nothing
if ̸= then: action to change state
Martin Schütte | Ansible Modules | DENOG 11 22/34
Check Mode/“Dry Run”
• Return information but never apply changes
• Optional, but recommended for modules
Example in hostname module:
def update_permanent_hostname(self):
name = self.module.params['name']
permanent_name = self.get_permanent_hostname()
if permanent_name != name:
if not self.module.check_mode:
self.set_permanent_hostname(name)
self.changed = True
Martin Schütte | Ansible Modules | DENOG 11 23/34
Diff Return Value
Example from hostname:
if changed:
kw['diff'] = {'after': 'hostname = ' + name + 'n',
'before': 'hostname = ' + name_before + 'n'}
Example output, sample module:
TASK [set hostname] *****************************************
--- before
+++ after
@@ -1 +1 @@
-hostname = workstation.example.org
+hostname = controller.example.org
changed: [workstation] => {”ansible_facts”: {...},
”changed”: true, ”name”: ”controller.example.org”}
Martin Schütte | Ansible Modules | DENOG 11 24/34
Set Facts
In a playbook:
- do_something:
# ...
register: result_var
- set_fact:
foo: ”{{ result_var.results | list }}”
In a module (from hostname):
kw = dict(changed=changed, name=name,
ansible_facts=dict(ansible_hostname=name.split('.')[0],
ansible_nodename=name,
ansible_fqdn=socket.getfqdn(),
ansible_domain='.'.join(
socket.getfqdn().split('.')[1:])))
module.exit_json(**kw)
Martin Schütte | Ansible Modules | DENOG 11 25/34
Pattern: Check Dependencies
try:
import psycopg2
import psycopg2.extras
except ImportError:
HAS_PSYCOPG2 = False
else:
HAS_PSYCOPG2 = True
def main():
module = AnsibleModule()
# ...
if not HAS_PSYCOPG2:
module.fail_json(
msg=”the python psycopg2 module is required”)
Martin Schütte | Ansible Modules | DENOG 11 26/34
Writing Modules
Debugging
Debugging Tools and Tips
Dev environment:
• Vagrant
• keep_remote_files = True
• ansible -vvv
Module tools:
• “print to output”
• AnsibleModule.log()
• q
Martin Schütte | Ansible Modules | DENOG 11 27/34
Debugging – printf
• Ansible reads stdin and stdout, expects JSON
⇒ cannot use print() to debug
• Use output values instead
# ...
debug_msg = ”some_func({}) returned {}”.format(bar, foo)
# ...
module.exit_json(result=foo, debug_msg=debug_msg)
ok: [server] => {
”changed”: false,
”debug_msg”: ”some_func(bar) returned foo”,
...
}
Martin Schütte | Ansible Modules | DENOG 11 28/34
Debugging – AnsibleModule log()
• AnsibleModule includes method log()
with variants debug() and warn()
• Writes to journald or Syslog
module.log(”Hello World”)
# tail /var/log/messages
Feb 9 15:02:59 server ansible-my_module: Invoked with param=...
Feb 9 15:02:59 server ansible-my_module: Hello World
Martin Schütte | Ansible Modules | DENOG 11 29/34
Debugging – q
• PyPI q or zestyping/q 
• Always writes to /tmp/q
• function decorators
try:
import q
except ImportError:
def q(x):
return x
@q
def my_func(params):
q(special_var)
# ...
$ tail /tmp/q
0.0s my_func('VERSION')
0.0s my_func: 'special_value'
0.0s -> {'failed': False, 'msg': '...'}
Martin Schütte | Ansible Modules | DENOG 11 30/34
Writing Modules
Beyond Python
Ansible Modules in Other Languages
• Python: the default choice, best tools and support. Also
required for network modules/plugins on controller.
• PowerShell: officially supported for modules on Windows
• Scripting Languages: work fine for modules, but lack
AnsibleModule standard library
• Binary Executables: possible but not practical. –
Instead install with OS package, then use command
or a thin wrapper module.
Martin Schütte | Ansible Modules | DENOG 11 31/34
Conclusion
Conclusion
• It is easy to write Python modules for Linux-like targets.
• Network devices are hard (connections, OS, CLI variation).
Community, Red Hat, and vendors are working on better
abstractions.
• Ansible project moves fast (release 2.9 ̸= 2.3 ̸= 1.8).
• Check Module Maintenance Levels.
• Core: Ansible Engineering Team
• Network: Ansible Network Team
• Certified: Ansible Partners
• Community
Martin Schütte | Ansible Modules | DENOG 11 32/34
Links
• Ansible Docs on “Modules:
Conventions, tips, and pitfalls”
• ansible/ansible 
• Ansible: Up & Running, 2nd ed
by Lorin Hochstein & René Moser
(covers Ansible 2.3)
• Ansible Docs on “Ansible for
Network Automation”
• Network Working Group,
ansible/community 
Martin Schütte | Ansible Modules | DENOG 11 33/34
The End
Thank You! — Questions?
Martin Schütte
@m_schuett 
info@martin-schuette.de 
slideshare.net/mschuett/ 
noti.st/mschuett/
Martin Schütte | Ansible Modules | DENOG 11 34/34

More Related Content

What's hot

Terraform 0.9 + good practices
Terraform 0.9 + good practicesTerraform 0.9 + good practices
Terraform 0.9 + good practicesRadek Simko
 
Infrastructure as Code: Introduction to Terraform
Infrastructure as Code: Introduction to TerraformInfrastructure as Code: Introduction to Terraform
Infrastructure as Code: Introduction to TerraformAlexander Popov
 
Terraform: Configuration Management for Cloud Services
Terraform: Configuration Management for Cloud ServicesTerraform: Configuration Management for Cloud Services
Terraform: Configuration Management for Cloud ServicesMartin Schütte
 
Introductory Overview to Managing AWS with Terraform
Introductory Overview to Managing AWS with TerraformIntroductory Overview to Managing AWS with Terraform
Introductory Overview to Managing AWS with TerraformMichael Heyns
 
"Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ..."Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ...Anton Babenko
 
Hashiconf EU 2019 - A Tour of Terraform 0.12
Hashiconf EU 2019 - A Tour of Terraform 0.12Hashiconf EU 2019 - A Tour of Terraform 0.12
Hashiconf EU 2019 - A Tour of Terraform 0.12Mitchell Pronschinske
 
Comprehensive Terraform Training
Comprehensive Terraform TrainingComprehensive Terraform Training
Comprehensive Terraform TrainingYevgeniy Brikman
 
Declarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with TerraformDeclarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with TerraformRadek Simko
 
Terraform at Scale - All Day DevOps 2017
Terraform at Scale - All Day DevOps 2017Terraform at Scale - All Day DevOps 2017
Terraform at Scale - All Day DevOps 2017Jonathon Brouse
 
Terraform modules and some of best-practices - March 2019
Terraform modules and some of best-practices - March 2019Terraform modules and some of best-practices - March 2019
Terraform modules and some of best-practices - March 2019Anton Babenko
 
Building infrastructure as code using Terraform - DevOps Krakow
Building infrastructure as code using Terraform - DevOps KrakowBuilding infrastructure as code using Terraform - DevOps Krakow
Building infrastructure as code using Terraform - DevOps KrakowAnton Babenko
 
Building infrastructure with Terraform (Google)
Building infrastructure with Terraform (Google)Building infrastructure with Terraform (Google)
Building infrastructure with Terraform (Google)Radek Simko
 
Scaling terraform
Scaling terraformScaling terraform
Scaling terraformPaolo Tonin
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introductionJason Vance
 
A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices Nebulaworks
 

What's hot (20)

Refactoring terraform
Refactoring terraformRefactoring terraform
Refactoring terraform
 
Terraform 0.9 + good practices
Terraform 0.9 + good practicesTerraform 0.9 + good practices
Terraform 0.9 + good practices
 
Infrastructure as Code: Introduction to Terraform
Infrastructure as Code: Introduction to TerraformInfrastructure as Code: Introduction to Terraform
Infrastructure as Code: Introduction to Terraform
 
Terraform: Configuration Management for Cloud Services
Terraform: Configuration Management for Cloud ServicesTerraform: Configuration Management for Cloud Services
Terraform: Configuration Management for Cloud Services
 
Introductory Overview to Managing AWS with Terraform
Introductory Overview to Managing AWS with TerraformIntroductory Overview to Managing AWS with Terraform
Introductory Overview to Managing AWS with Terraform
 
"Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ..."Continuously delivering infrastructure using Terraform and Packer" training ...
"Continuously delivering infrastructure using Terraform and Packer" training ...
 
Hashiconf EU 2019 - A Tour of Terraform 0.12
Hashiconf EU 2019 - A Tour of Terraform 0.12Hashiconf EU 2019 - A Tour of Terraform 0.12
Hashiconf EU 2019 - A Tour of Terraform 0.12
 
Intro to Terraform
Intro to TerraformIntro to Terraform
Intro to Terraform
 
Comprehensive Terraform Training
Comprehensive Terraform TrainingComprehensive Terraform Training
Comprehensive Terraform Training
 
Everything as Code with Terraform
Everything as Code with TerraformEverything as Code with Terraform
Everything as Code with Terraform
 
Declarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with TerraformDeclarative & workflow based infrastructure with Terraform
Declarative & workflow based infrastructure with Terraform
 
02 terraform core concepts
02 terraform core concepts02 terraform core concepts
02 terraform core concepts
 
Terraform at Scale
Terraform at ScaleTerraform at Scale
Terraform at Scale
 
Terraform at Scale - All Day DevOps 2017
Terraform at Scale - All Day DevOps 2017Terraform at Scale - All Day DevOps 2017
Terraform at Scale - All Day DevOps 2017
 
Terraform modules and some of best-practices - March 2019
Terraform modules and some of best-practices - March 2019Terraform modules and some of best-practices - March 2019
Terraform modules and some of best-practices - March 2019
 
Building infrastructure as code using Terraform - DevOps Krakow
Building infrastructure as code using Terraform - DevOps KrakowBuilding infrastructure as code using Terraform - DevOps Krakow
Building infrastructure as code using Terraform - DevOps Krakow
 
Building infrastructure with Terraform (Google)
Building infrastructure with Terraform (Google)Building infrastructure with Terraform (Google)
Building infrastructure with Terraform (Google)
 
Scaling terraform
Scaling terraformScaling terraform
Scaling terraform
 
Terraform introduction
Terraform introductionTerraform introduction
Terraform introduction
 
A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices A Hands-on Introduction on Terraform Best Concepts and Best Practices
A Hands-on Introduction on Terraform Best Concepts and Best Practices
 

Similar to Writing Ansible Modules (DENOG11)

Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and ContainersRodolfo Carvalho
 
Symfony2 Introduction Presentation
Symfony2 Introduction PresentationSymfony2 Introduction Presentation
Symfony2 Introduction PresentationNerd Tzanetopoulos
 
Drupal 8 - Core and API Changes
Drupal 8 - Core and API ChangesDrupal 8 - Core and API Changes
Drupal 8 - Core and API ChangesShabir Ahmad
 
Ansible new paradigms for orchestration
Ansible new paradigms for orchestrationAnsible new paradigms for orchestration
Ansible new paradigms for orchestrationPaolo Tonin
 
A tour of Ansible
A tour of AnsibleA tour of Ansible
A tour of AnsibleDevOps Ltd.
 
Portland Puppet User Group June 2014: Writing and publishing puppet modules
Portland Puppet User Group June 2014: Writing and publishing puppet modulesPortland Puppet User Group June 2014: Writing and publishing puppet modules
Portland Puppet User Group June 2014: Writing and publishing puppet modulesPuppet
 
June 2014 PDX PUG: Writing and Publishing Puppet Modules
June 2014 PDX PUG: Writing and Publishing Puppet Modules June 2014 PDX PUG: Writing and Publishing Puppet Modules
June 2014 PDX PUG: Writing and Publishing Puppet Modules Puppet
 
The state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinNida Ismail Shah
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php PresentationAlan Pinstein
 
Applying software engineering to configuration management
Applying software engineering to configuration managementApplying software engineering to configuration management
Applying software engineering to configuration managementBart Vanbrabant
 
Php7 extensions workshop
Php7 extensions workshopPhp7 extensions workshop
Php7 extensions workshopjulien pauli
 
Chef arista devops days a'dam 2015
Chef arista devops days a'dam 2015Chef arista devops days a'dam 2015
Chef arista devops days a'dam 2015Edwin Beekman
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practicesmanugoel2003
 
MariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructuresMariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructuresFederico Razzoli
 
Mobyle administrator workshop
Mobyle administrator workshopMobyle administrator workshop
Mobyle administrator workshopbneron
 
Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)Chu-Siang Lai
 
2019 11-bgphp
2019 11-bgphp2019 11-bgphp
2019 11-bgphpdantleech
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Codeerikmsp
 

Similar to Writing Ansible Modules (DENOG11) (20)

Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
 
Symfony2 Introduction Presentation
Symfony2 Introduction PresentationSymfony2 Introduction Presentation
Symfony2 Introduction Presentation
 
Drupal 8 - Core and API Changes
Drupal 8 - Core and API ChangesDrupal 8 - Core and API Changes
Drupal 8 - Core and API Changes
 
Ansible new paradigms for orchestration
Ansible new paradigms for orchestrationAnsible new paradigms for orchestration
Ansible new paradigms for orchestration
 
A tour of Ansible
A tour of AnsibleA tour of Ansible
A tour of Ansible
 
Portland Puppet User Group June 2014: Writing and publishing puppet modules
Portland Puppet User Group June 2014: Writing and publishing puppet modulesPortland Puppet User Group June 2014: Writing and publishing puppet modules
Portland Puppet User Group June 2014: Writing and publishing puppet modules
 
June 2014 PDX PUG: Writing and Publishing Puppet Modules
June 2014 PDX PUG: Writing and Publishing Puppet Modules June 2014 PDX PUG: Writing and Publishing Puppet Modules
June 2014 PDX PUG: Writing and Publishing Puppet Modules
 
The state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon Dublin
 
One-Man Ops
One-Man OpsOne-Man Ops
One-Man Ops
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
Applying software engineering to configuration management
Applying software engineering to configuration managementApplying software engineering to configuration management
Applying software engineering to configuration management
 
Php7 extensions workshop
Php7 extensions workshopPhp7 extensions workshop
Php7 extensions workshop
 
Chef arista devops days a'dam 2015
Chef arista devops days a'dam 2015Chef arista devops days a'dam 2015
Chef arista devops days a'dam 2015
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
MariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructuresMariaDB, MySQL and Ansible: automating database infrastructures
MariaDB, MySQL and Ansible: automating database infrastructures
 
Mobyle administrator workshop
Mobyle administrator workshopMobyle administrator workshop
Mobyle administrator workshop
 
Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)
 
2019 11-bgphp
2019 11-bgphp2019 11-bgphp
2019 11-bgphp
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
 
Puppet quick start guide
Puppet quick start guidePuppet quick start guide
Puppet quick start guide
 

More from Martin Schütte

The IPv6 Snort Plugin (at DeepSec 2014)
The IPv6 Snort Plugin (at DeepSec 2014)The IPv6 Snort Plugin (at DeepSec 2014)
The IPv6 Snort Plugin (at DeepSec 2014)Martin Schütte
 
The IPv6 Snort Plugin (at Troopers 14 IPv6 Security Summit)
The IPv6 Snort Plugin (at Troopers 14 IPv6 Security Summit)The IPv6 Snort Plugin (at Troopers 14 IPv6 Security Summit)
The IPv6 Snort Plugin (at Troopers 14 IPv6 Security Summit)Martin Schütte
 
Short Introduction to IPv6
Short Introduction to IPv6Short Introduction to IPv6
Short Introduction to IPv6Martin Schütte
 
Software Testing on the Web
Software Testing on the WebSoftware Testing on the Web
Software Testing on the WebMartin Schütte
 
NetBSD syslogd with IETF Syslog Protocols
NetBSD syslogd with IETF Syslog ProtocolsNetBSD syslogd with IETF Syslog Protocols
NetBSD syslogd with IETF Syslog ProtocolsMartin Schütte
 
Design and Implementation of an IPv6 Plugin for the Snort Intrusion Detection...
Design and Implementation of an IPv6 Plugin for the Snort Intrusion Detection...Design and Implementation of an IPv6 Plugin for the Snort Intrusion Detection...
Design and Implementation of an IPv6 Plugin for the Snort Intrusion Detection...Martin Schütte
 

More from Martin Schütte (8)

The IPv6 Snort Plugin (at DeepSec 2014)
The IPv6 Snort Plugin (at DeepSec 2014)The IPv6 Snort Plugin (at DeepSec 2014)
The IPv6 Snort Plugin (at DeepSec 2014)
 
The IPv6 Snort Plugin (at Troopers 14 IPv6 Security Summit)
The IPv6 Snort Plugin (at Troopers 14 IPv6 Security Summit)The IPv6 Snort Plugin (at Troopers 14 IPv6 Security Summit)
The IPv6 Snort Plugin (at Troopers 14 IPv6 Security Summit)
 
Short Introduction to IPv6
Short Introduction to IPv6Short Introduction to IPv6
Short Introduction to IPv6
 
Software Testing on the Web
Software Testing on the WebSoftware Testing on the Web
Software Testing on the Web
 
NetBSD syslogd with IETF Syslog Protocols
NetBSD syslogd with IETF Syslog ProtocolsNetBSD syslogd with IETF Syslog Protocols
NetBSD syslogd with IETF Syslog Protocols
 
PGP/GPG Einführung
PGP/GPG EinführungPGP/GPG Einführung
PGP/GPG Einführung
 
Design and Implementation of an IPv6 Plugin for the Snort Intrusion Detection...
Design and Implementation of an IPv6 Plugin for the Snort Intrusion Detection...Design and Implementation of an IPv6 Plugin for the Snort Intrusion Detection...
Design and Implementation of an IPv6 Plugin for the Snort Intrusion Detection...
 
Syslog Protocols
Syslog ProtocolsSyslog Protocols
Syslog Protocols
 

Recently uploaded

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Recently uploaded (20)

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 

Writing Ansible Modules (DENOG11)

  • 1. Writing Ansible Modules Martin Schütte 11 November 2019
  • 2. Assumptions You … • configure servers or network devices • have already seen Ansible config • can write shell scripts This talk … • is no Ansible how-to • has more slides online • is available on noti.st Martin Schütte | Ansible Modules | DENOG 11 2/34
  • 3. Outline 1. Concepts Module Basics Orchestration with Host Delegation 2. Writing Modules Simple Example: ipify API Patterns & Misc. Hints Debugging Beyond Python 3. Conclusion Martin Schütte | Ansible Modules | DENOG 11 3/34
  • 6. Ansible – Concepts and Naming Ansible is a radically simple IT automation platform. • controller • target host • playbook • role • task • module Martin Schütte | Ansible Modules | DENOG 11 4/34
  • 7. Example: Simple Playbook --- - hosts: webserver vars: apache_version: latest tasks: - name: ensure apache is at given version yum: name: httpd state: ”{{ apache_version }}” - hosts: dbserver roles: - ansible-role-postgresql Martin Schütte | Ansible Modules | DENOG 11 5/34
  • 9. What is a Module? some code snippet to run on the (remote) host executable with input and output Martin Schütte | Ansible Modules | DENOG 11 6/34
  • 10. Minimal Module #!/bin/sh echo '{”foo”: ”bar”}' exit 0 #!/usr/bin/python if __name__ == '__main__': print('{”foo”: ”bar”}') exit(0) Martin Schütte | Ansible Modules | DENOG 11 7/34
  • 11. Action Plugins call Modules • plugins run on the controller • may prepare input for modules • may handle “special” connections (non SSH or WinRM) • defaults to normal to run module on target host Martin Schütte | Ansible Modules | DENOG 11 8/34
  • 13. normal SSH Target # in Playbook - hosts: webserver tasks: - name: webserver reload service: name: httpd state: reloaded Martin Schütte | Ansible Modules | DENOG 11 9/34
  • 14. normal SSH Target, with delegate_to - hosts: webserver tasks: - name: webserver reload # ... - name: loadbalancer reload delegate_to: loadbalancer service: name: nginx state: reloaded Martin Schütte | Ansible Modules | DENOG 11 10/34
  • 15. Network, Vendor Specific junos_command - hosts: router tasks: - name: get interfaces connection: local junos_command: command: show interface terse provider: host: router username: foo Martin Schütte | Ansible Modules | DENOG 11 11/34
  • 16. Network, New Generic cli_command - hosts: router tasks: - name: get interfaces cli_command: command: show interface terse # uses Ansible inventory to read variables # ansible_network_os=junos, ansible_connection=network_cli, # ansible_user, ansible_password, ansible_ssh_common_args Martin Schütte | Ansible Modules | DENOG 11 12/34
  • 19. Avoid Writing Own Code • get_url – Downloads files • uri – Interacts with webservices • wait_for – Waits for a condition before continuing • set_fact – Set host facts from a task - name: Wait for port 8000 to become open on the host wait_for: port: 8000 delay: 10 - name: wait for service to become available uri: url: 'https://{{ inventory_hostname }}:{{ svc_port }}/service' return_content: yes register: content until: content.status == 200 retries: 60 delay: 10 when: not ansible_check_mode Martin Schütte | Ansible Modules | DENOG 11 13/34
  • 21. Documentation ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: ipify_facts short_description: Retrieve the public IP of your internet gateway version_added: '2.0' options: api_url: ... ''' EXAMPLES = r''' # Gather IP facts from ipify.org - name: Get my public IP ipify_facts: # Gather IP facts from your own ipify service endpoint with a custom timeout - name: Get my public IP ipify_facts: api_url: http://api.example.com/ipify timeout: 20 ''' RETURN = ... Martin Schütte | Ansible Modules | DENOG 11 14/34
  • 22. ansible-doc $ ansible-doc --snippet ipify_facts - name: Retrieve the public IP of your internet gateway ipify_facts: api_url: # URL of the ipify.org API service. timeout: # HTTP connection timeout in seconds. validate_certs: # When set to `NO', SSL certificates will not be validated. $ ansible-doc ipify_facts > IPIFY_FACTS (.../site-packages/ansible/modules/net_tools/ipify_facts.py) If behind NAT and need to know the public IP of your internet gateway. * This module is maintained by The Ansible Community OPTIONS (= is mandatory): - api_url URL of the ipify.org API service. `?format=json' will be appended per default. [Default: https://api.ipify.org/] type: str ... Martin Schütte | Ansible Modules | DENOG 11 15/34
  • 23. ipify_facts.py def main(): global module module = AnsibleModule( argument_spec=dict( api_url=dict(type='str', default='https://api.ipify.org/'), timeout=dict(type='int', default=10), validate_certs=dict(type='bool', default=True), ), supports_check_mode=True, ) ipify_facts = IpifyFacts().run() ipify_facts_result = dict(changed=False, ansible_facts=ipify_facts) module.exit_json(**ipify_facts_result) if __name__ == '__main__': main() Martin Schütte | Ansible Modules | DENOG 11 16/34
  • 24. ipify_facts.py class IpifyFacts(object): def __init__(self): self.api_url = module.params.get('api_url') self.timeout = module.params.get('timeout') def run(self): result = { 'ipify_public_ip': None } (response, info) = fetch_url(module=module, url=self.api_url + ”?format=json”, force=True, timeout=self.timeout) if not response: module.fail_json(msg=”No valid or no response ...”) data = json.loads(to_text(response.read())) result['ipify_public_ip'] = data.get('ip') return result Martin Schütte | Ansible Modules | DENOG 11 17/34
  • 25. Usage in Tasks - name: get IP from alternative service endpoint ipify_facts: api_url: https://api6.ipify.org register: ip_public - name: debug output debug: msg: | fact: {{ ipify_public_ip }} reg: {{ ip_public.ansible_facts.ipify_public_ip }} TASK [my_role : debug output] ********************** ok: [server] => { ”msg”: ”fact: 2001:db8:1:2::42nreg: 2001:db8:1:2::42n” } Martin Schütte | Ansible Modules | DENOG 11 18/34
  • 27. my_module.py from ansible.module_utils.basic import AnsibleModule def main(): module = AnsibleModule( argument_spec=dict( # ... ) ) rc = do_something() result = { ”msg”: ”Hello World”, ”rc”: rc, ”failed”: False, ”changed”: False, } module.exit_json(**result) if __name__ == '__main__': main() Martin Schütte | Ansible Modules | DENOG 11 19/34
  • 28. File Locations: library and module_utils my_role/ meta defaults tasks library my_module.py module_utils my_util_lib.py • role can use Ansible module my_module in tasks • import * from my_util_lib finds Python module in module_utils • for “larger” libraries use packages (pip/rpm/dpkg) Martin Schütte | Ansible Modules | DENOG 11 20/34
  • 29. “standard library” AnsibleModule Useful common methods: • argument_spec for parameters • supports_check_mode • exit_json(), fail_json() • atomic_move(), run_command() • bytes_to_human(), human_to_bytes() Other module_utils: • api: function/decorator @rate_limit() • timeout: function/decorator @timeout(secs) Martin Schütte | Ansible Modules | DENOG 11 21/34
  • 30. Pattern: Idempotency • Playbooks can run many times • As few changes as possible • Only perform required actions 1. Get spec parameters 2. Check actual state of system if = then: done, do nothing if ̸= then: action to change state Martin Schütte | Ansible Modules | DENOG 11 22/34
  • 31. Check Mode/“Dry Run” • Return information but never apply changes • Optional, but recommended for modules Example in hostname module: def update_permanent_hostname(self): name = self.module.params['name'] permanent_name = self.get_permanent_hostname() if permanent_name != name: if not self.module.check_mode: self.set_permanent_hostname(name) self.changed = True Martin Schütte | Ansible Modules | DENOG 11 23/34
  • 32. Diff Return Value Example from hostname: if changed: kw['diff'] = {'after': 'hostname = ' + name + 'n', 'before': 'hostname = ' + name_before + 'n'} Example output, sample module: TASK [set hostname] ***************************************** --- before +++ after @@ -1 +1 @@ -hostname = workstation.example.org +hostname = controller.example.org changed: [workstation] => {”ansible_facts”: {...}, ”changed”: true, ”name”: ”controller.example.org”} Martin Schütte | Ansible Modules | DENOG 11 24/34
  • 33. Set Facts In a playbook: - do_something: # ... register: result_var - set_fact: foo: ”{{ result_var.results | list }}” In a module (from hostname): kw = dict(changed=changed, name=name, ansible_facts=dict(ansible_hostname=name.split('.')[0], ansible_nodename=name, ansible_fqdn=socket.getfqdn(), ansible_domain='.'.join( socket.getfqdn().split('.')[1:]))) module.exit_json(**kw) Martin Schütte | Ansible Modules | DENOG 11 25/34
  • 34. Pattern: Check Dependencies try: import psycopg2 import psycopg2.extras except ImportError: HAS_PSYCOPG2 = False else: HAS_PSYCOPG2 = True def main(): module = AnsibleModule() # ... if not HAS_PSYCOPG2: module.fail_json( msg=”the python psycopg2 module is required”) Martin Schütte | Ansible Modules | DENOG 11 26/34
  • 36. Debugging Tools and Tips Dev environment: • Vagrant • keep_remote_files = True • ansible -vvv Module tools: • “print to output” • AnsibleModule.log() • q Martin Schütte | Ansible Modules | DENOG 11 27/34
  • 37. Debugging – printf • Ansible reads stdin and stdout, expects JSON ⇒ cannot use print() to debug • Use output values instead # ... debug_msg = ”some_func({}) returned {}”.format(bar, foo) # ... module.exit_json(result=foo, debug_msg=debug_msg) ok: [server] => { ”changed”: false, ”debug_msg”: ”some_func(bar) returned foo”, ... } Martin Schütte | Ansible Modules | DENOG 11 28/34
  • 38. Debugging – AnsibleModule log() • AnsibleModule includes method log() with variants debug() and warn() • Writes to journald or Syslog module.log(”Hello World”) # tail /var/log/messages Feb 9 15:02:59 server ansible-my_module: Invoked with param=... Feb 9 15:02:59 server ansible-my_module: Hello World Martin Schütte | Ansible Modules | DENOG 11 29/34
  • 39. Debugging – q • PyPI q or zestyping/q  • Always writes to /tmp/q • function decorators try: import q except ImportError: def q(x): return x @q def my_func(params): q(special_var) # ... $ tail /tmp/q 0.0s my_func('VERSION') 0.0s my_func: 'special_value' 0.0s -> {'failed': False, 'msg': '...'} Martin Schütte | Ansible Modules | DENOG 11 30/34
  • 41. Ansible Modules in Other Languages • Python: the default choice, best tools and support. Also required for network modules/plugins on controller. • PowerShell: officially supported for modules on Windows • Scripting Languages: work fine for modules, but lack AnsibleModule standard library • Binary Executables: possible but not practical. – Instead install with OS package, then use command or a thin wrapper module. Martin Schütte | Ansible Modules | DENOG 11 31/34
  • 43. Conclusion • It is easy to write Python modules for Linux-like targets. • Network devices are hard (connections, OS, CLI variation). Community, Red Hat, and vendors are working on better abstractions. • Ansible project moves fast (release 2.9 ̸= 2.3 ̸= 1.8). • Check Module Maintenance Levels. • Core: Ansible Engineering Team • Network: Ansible Network Team • Certified: Ansible Partners • Community Martin Schütte | Ansible Modules | DENOG 11 32/34
  • 44. Links • Ansible Docs on “Modules: Conventions, tips, and pitfalls” • ansible/ansible  • Ansible: Up & Running, 2nd ed by Lorin Hochstein & René Moser (covers Ansible 2.3) • Ansible Docs on “Ansible for Network Automation” • Network Working Group, ansible/community  Martin Schütte | Ansible Modules | DENOG 11 33/34
  • 45. The End Thank You! — Questions? Martin Schütte @m_schuett  info@martin-schuette.de  slideshare.net/mschuett/  noti.st/mschuett/ Martin Schütte | Ansible Modules | DENOG 11 34/34