SlideShare uma empresa Scribd logo
1 de 24
© 2014 VMware Inc. All rights reserved.© 2014 VMware Inc. All rights reserved.
22/02/2016
Ansible Module Development 101
Yves Fauser
Technical Product Manager @ VMware
Who is standing in front of you?
• I’m working with VMware’s network virtualization product called NSX
• I’m the co-organizer for this Meetup & the OpenStack Munich Meetup group
• I’m living in Munich since 14 years
• I’ve spend 3 years working at VMware as Systems Engineer & Solution Architect,
7 years as a Systems Engineer at Cisco, and I was a networking / OS consultant and
developer before
• Topics I love to discuss and work with:
Configuration Management, Automation, Containers / ‘Cloud’, OpenStack, Networking, ...
Yves Fauser
Technical Product Manager @ VMware
Why developing your own Modules
• There are tons of great build-in core and extra modules for Ansible – So why build your own?
• Generally if you only work with Files, Packages and Services on standard OSs you are
covered, and there is no need to develop your own stuff
• But sometimes you want to do ‘strange stuff’, and then making this idempotent is hard, e.g.
• You might want to interact with APIs of products and ‘cloud services’
• You might want to use commands / CLIs that were not build to work well with configuration
management (e.g. that don’t implement granular return codes but give you lots of stdout garbage)
• I had to do both, interact with an API and use CLI tools with a lot of stdout that I needed to
interpret
• Working with the VMware NSX API
• Using VMware’s OVFTool to deploy VMs into vCenter *
* We will show the use the OVFTool Module as an example later
Why using Python to develop Modules
• Ansible generally supports writing Modules in any language, e.g Python, C, Ruby, Shell, Go, …
• The only requirements are:
• The language needs to be able to implement File I/O
• The language needs to be able write JSON formatted output to STDOUT
• Why I am using Python:
• First and foremost, I’m a Pythonist – I really like this language
• Ansible itself and all its core Modules are written in Python – You have a lot to read and learn from!
• There are very easy and ready to use ‘boilerplates’ and ‘helper functions’ for Ansible written for Python
• Besides Python, the second most often used language is shell script
Getting started – a few important bits of knowledge
• When writing a custom module
you call it from a Play like this:
• Alternatively you can use ‘action’
• In this case ‘test_module’ can be
test_module.py, or test_module.sh,
test_module.<you_name_it> in the
library path
• Ansible searches for modules the path specified by ANSIBLE_LIBRARY or the --module-path
command line option
• The directory ”./library”, alongside your
top level playbooks, is also automatically
added as a search directory
• I personally always use the “./library”
option when developing modules
Getting started – The ‘boilerplate’ code of every module
• You always start with a boilerplate code like this:
Uuuhh … that’s ugly, an
import statement at the
bottom of the file, and
importing *, that’s against all
python style guides!
Why’s that?
Ansible code creation
• You module code is not the final code that gets executed
• Ansible takes the code and constructs a single Python script that gets copied to the remote
system and then executed. The statement ‘from ansible.module_utils.basic import *’
imports ~1600 lines of code into this final script
Ansible code creation
Here’s the place were it
inserts the Ansible Module
code after your code
And the function main() is
called right at the end of the
code
Getting started – The Module argument_spec dictionary
mandatory variable
mandatory variable, do no log (e.g. passwords)
mandatory variable, with fixed possible values
optional variable taking any value
optional variables checked for existence later
variable having a default value
variable with a strict type
variable with an alias
checks if at least one variable in the list is present
ensures that only one of two variables are set
Getting started – The Module argument_spec dictionary
• You can access the modules parameters dictionary with ‘module.params[‘key’]’
Exiting the module
• Exiting the module is done using
‘module.exit_json’ for successful returns,
and ‘module.fail_json’ to fail the task
Exit the module with the changed flag set and
with additional variables returned to the Play
Exit the module successfully, but
signaling that there was no change
Exit the module with a failure
Putting it to work – Example Module
• I love to go running, but not when it’s too cold. I will let Ansible decide for me
You can find the code here: https://gist.github.com/yfauser/90c0955827c74d83d6a2
If the temperature returned by Open Weather
Map in my city is bellow my threshold –
I’ll stay at home (keep my current state)
If the temperature returned by Open Weather
Map in my city is above my threshold – I’ll
leave the house (change my state)
Putting it to work – The If / Elif / Else way
Putting it to work – Catching errors
• OK, but what about failed states?
Let’s enhance our code a bit
Using try/except as well as http status codes
as indications of failed conditions
Putting it to work – Catching errors
 Here we are passing the module
to the sub-function to call
module.fail_json inside of it
Use OS commands with Python based Modules
• The python Ansible base code has a great method to interact with the OS
• The difference from running this inside of your python based module instead of ‘command’ in
your Play is that you can interpret the output returned by the OS command more flexibly
• The response object will be a list with two items:
• [0] holds the return code of the command as an integer, so you can react based on the return code
• [1] holds the stdout of the command as a string – So you can do things like:
• Pass it to parsers like ‘json.loads’ to convert it to dictionaries
• Search in it with ‘.find’
• Count, sort, pass it through regexp, etc.
Use OS commands with Python based Modules
• Lets change our example to
use OS commands (curl)
format the owm url with all mandatory
url parameters
use the OS command curl to send
the request
check if curl gave a positive return code
check if we received a positive ret. code
convert curl stdout to a python dict
extract temperature value from dict
You can find the code here:
https://gist.github.com/yfauser/b2377e
ee842a1cd2a899
Use OS commands with Python based Modules
• Here’s another real life example of using the OS command option
• This code uses
module.run_command
to invoke the
ovftool to deploy
a VM into
vCenter
You can find the code here:
https://github.com/vmware/nsxansible/blob/master/library/nsx_deploy_ova.py
Debugging your module
• What is the #1 tool for debugging Python code? => ‘print’ ;-)
• Unfortunately sending non-JSON
formatted output to stdout will not
result in any output on the console
when running your Play:
• Modules must also not output anything on standard error, because the system will merge
standard out with standard error and prevent the JSON from parsing. Capturing standard
error and returning it as a variable in the JSON on standard out is fine, and is, in fact, how the
command module is implemented
• In short => Never use ‘print’
Debugging your module code
• Instead of printing to stdout, send your debug data into a variable (e.g. a list) and
pass it to the module.exit_json or
module.fail_json method:
What’s this ‘supports_check_mode’ about?
• Ansible Playbooks can run in check-mode
using the --check option
• If ‘supports_check_mode’ is set to:
• ‘True’: It’s up to you to make sure your module doesn’t
apply changes, but only checks if it would have made
changes if Ansible runs in check mode
• ‘False’ or unset: The task using your module will
be skipped if Ansible runs in check mode
Inline Documentation
• Ansible supports the generation of module
documentation on their Web-Site from
inline Documentation in the module code
• You can read about all the details here:
http://docs.ansible.com/ansible/developing_
modules.html#documenting-your-module
Developing Ansible Modules on a MAC
• When developing a python based module on a MAC you might run into this:
• When you run the module it fails to import
libraries because it doesn’t use the right
interpreter and path
• Solution 1, use the ‘#!/usr/bin/env python’ shebang instead of ‘#!/usr/bin/python’:
• Don’t use this! As it’s an anti-pattern if you want to get this into ansible-modules-extra or core
 Solution 2, define the interpreter path in the hosts file
 This is the proper solution as this solves it on a per host level for those systems that need it
Questions?
Check out some more of my stuff here:
https://github.com/vmware/nsxansible/

Mais conteúdo relacionado

Mais procurados

[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...OpenStack Korea Community
 
Docker and Kubernetes 101 workshop
Docker and Kubernetes 101 workshopDocker and Kubernetes 101 workshop
Docker and Kubernetes 101 workshopSathish VJ
 
Openstack live migration
Openstack live migrationOpenstack live migration
Openstack live migrationymtech
 
How to write a Dockerfile
How to write a DockerfileHow to write a Dockerfile
How to write a DockerfileKnoldus Inc.
 
Red Hat Openshift Fundamentals.pptx
Red Hat Openshift Fundamentals.pptxRed Hat Openshift Fundamentals.pptx
Red Hat Openshift Fundamentals.pptxssuser18b1c6
 
Build automated Machine Images using Packer
Build automated Machine Images using PackerBuild automated Machine Images using Packer
Build automated Machine Images using PackerMarek Piątek
 
Jenkins tutorial for beginners
Jenkins tutorial for beginnersJenkins tutorial for beginners
Jenkins tutorial for beginnersBugRaptors
 
OpenShift Overview
OpenShift OverviewOpenShift Overview
OpenShift Overviewroundman
 
OpenShift 4, the smarter Kubernetes platform
OpenShift 4, the smarter Kubernetes platformOpenShift 4, the smarter Kubernetes platform
OpenShift 4, the smarter Kubernetes platformKangaroot
 
Testing Ansible with Jenkins and Docker
Testing Ansible with Jenkins and DockerTesting Ansible with Jenkins and Docker
Testing Ansible with Jenkins and DockerDennis Rowe
 

Mais procurados (20)

[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
 
Docker
DockerDocker
Docker
 
Docker and Kubernetes 101 workshop
Docker and Kubernetes 101 workshopDocker and Kubernetes 101 workshop
Docker and Kubernetes 101 workshop
 
Openstack live migration
Openstack live migrationOpenstack live migration
Openstack live migration
 
Packer by HashiCorp
Packer by HashiCorpPacker by HashiCorp
Packer by HashiCorp
 
How to write a Dockerfile
How to write a DockerfileHow to write a Dockerfile
How to write a Dockerfile
 
Docker in real life
Docker in real lifeDocker in real life
Docker in real life
 
A quick introduction to AKS
A quick introduction to AKSA quick introduction to AKS
A quick introduction to AKS
 
Red Hat Openshift Fundamentals.pptx
Red Hat Openshift Fundamentals.pptxRed Hat Openshift Fundamentals.pptx
Red Hat Openshift Fundamentals.pptx
 
Build automated Machine Images using Packer
Build automated Machine Images using PackerBuild automated Machine Images using Packer
Build automated Machine Images using Packer
 
Ansible
AnsibleAnsible
Ansible
 
Helm intro
Helm introHelm intro
Helm intro
 
Jenkins tutorial for beginners
Jenkins tutorial for beginnersJenkins tutorial for beginners
Jenkins tutorial for beginners
 
OpenShift Overview
OpenShift OverviewOpenShift Overview
OpenShift Overview
 
OpenShift Enterprise
OpenShift EnterpriseOpenShift Enterprise
OpenShift Enterprise
 
OpenShift 4, the smarter Kubernetes platform
OpenShift 4, the smarter Kubernetes platformOpenShift 4, the smarter Kubernetes platform
OpenShift 4, the smarter Kubernetes platform
 
Testing Ansible with Jenkins and Docker
Testing Ansible with Jenkins and DockerTesting Ansible with Jenkins and Docker
Testing Ansible with Jenkins and Docker
 
Ansible
AnsibleAnsible
Ansible
 
ansible why ?
ansible why ?ansible why ?
ansible why ?
 
Rancher Labs - Your own PaaS in action
Rancher Labs - Your own PaaS in actionRancher Labs - Your own PaaS in action
Rancher Labs - Your own PaaS in action
 

Destaque

Debugging ansible modules
Debugging ansible modulesDebugging ansible modules
Debugging ansible modulesaleonhardt
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentationJohn Lynch
 
Introduction to Ansible (Pycon7 2016)
Introduction to Ansible (Pycon7 2016)Introduction to Ansible (Pycon7 2016)
Introduction to Ansible (Pycon7 2016)Ivan Rossi
 
Ansible Introduction
Ansible Introduction Ansible Introduction
Ansible Introduction Robert Reiz
 
Ansible tips & tricks
Ansible tips & tricksAnsible tips & tricks
Ansible tips & tricksbcoca
 
ansible-playbook useful command line options
ansible-playbook useful command line optionsansible-playbook useful command line options
ansible-playbook useful command line optionsshirou wakayama
 
Herd your chickens: Ansible for DB2 configuration management
Herd your chickens: Ansible for DB2 configuration managementHerd your chickens: Ansible for DB2 configuration management
Herd your chickens: Ansible for DB2 configuration managementFrederik Engelen
 
Automated OVA deployments using OpenStack infrastructure
Automated OVA deployments using OpenStack infrastructureAutomated OVA deployments using OpenStack infrastructure
Automated OVA deployments using OpenStack infrastructureYolanda Robla
 
OVF, OVA, ovftool
OVF, OVA, ovftoolOVF, OVA, ovftool
OVF, OVA, ovftooltshiroyama
 
Hacking ansible
Hacking ansibleHacking ansible
Hacking ansiblebcoca
 
Continous delivery at docker age
Continous delivery at docker ageContinous delivery at docker age
Continous delivery at docker ageAdrien Blind
 
Local Dev on Virtual Machines - Vagrant, VirtualBox and Ansible
Local Dev on Virtual Machines - Vagrant, VirtualBox and AnsibleLocal Dev on Virtual Machines - Vagrant, VirtualBox and Ansible
Local Dev on Virtual Machines - Vagrant, VirtualBox and AnsibleJeff Geerling
 
運用のためのPlaybook (Playbook for Operation)
運用のためのPlaybook (Playbook for Operation)運用のためのPlaybook (Playbook for Operation)
運用のためのPlaybook (Playbook for Operation)Shingo Kitayama
 
Automated Deployments with Ansible
Automated Deployments with AnsibleAutomated Deployments with Ansible
Automated Deployments with AnsibleMartin Etmajer
 
V2 and beyond
V2 and beyondV2 and beyond
V2 and beyondjimi-c
 
Go Faster with Ansible (AWS meetup)
Go Faster with Ansible (AWS meetup)Go Faster with Ansible (AWS meetup)
Go Faster with Ansible (AWS meetup)Richard Donkin
 
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpecTest-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpecMartin Etmajer
 

Destaque (17)

Debugging ansible modules
Debugging ansible modulesDebugging ansible modules
Debugging ansible modules
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
 
Introduction to Ansible (Pycon7 2016)
Introduction to Ansible (Pycon7 2016)Introduction to Ansible (Pycon7 2016)
Introduction to Ansible (Pycon7 2016)
 
Ansible Introduction
Ansible Introduction Ansible Introduction
Ansible Introduction
 
Ansible tips & tricks
Ansible tips & tricksAnsible tips & tricks
Ansible tips & tricks
 
ansible-playbook useful command line options
ansible-playbook useful command line optionsansible-playbook useful command line options
ansible-playbook useful command line options
 
Herd your chickens: Ansible for DB2 configuration management
Herd your chickens: Ansible for DB2 configuration managementHerd your chickens: Ansible for DB2 configuration management
Herd your chickens: Ansible for DB2 configuration management
 
Automated OVA deployments using OpenStack infrastructure
Automated OVA deployments using OpenStack infrastructureAutomated OVA deployments using OpenStack infrastructure
Automated OVA deployments using OpenStack infrastructure
 
OVF, OVA, ovftool
OVF, OVA, ovftoolOVF, OVA, ovftool
OVF, OVA, ovftool
 
Hacking ansible
Hacking ansibleHacking ansible
Hacking ansible
 
Continous delivery at docker age
Continous delivery at docker ageContinous delivery at docker age
Continous delivery at docker age
 
Local Dev on Virtual Machines - Vagrant, VirtualBox and Ansible
Local Dev on Virtual Machines - Vagrant, VirtualBox and AnsibleLocal Dev on Virtual Machines - Vagrant, VirtualBox and Ansible
Local Dev on Virtual Machines - Vagrant, VirtualBox and Ansible
 
運用のためのPlaybook (Playbook for Operation)
運用のためのPlaybook (Playbook for Operation)運用のためのPlaybook (Playbook for Operation)
運用のためのPlaybook (Playbook for Operation)
 
Automated Deployments with Ansible
Automated Deployments with AnsibleAutomated Deployments with Ansible
Automated Deployments with Ansible
 
V2 and beyond
V2 and beyondV2 and beyond
V2 and beyond
 
Go Faster with Ansible (AWS meetup)
Go Faster with Ansible (AWS meetup)Go Faster with Ansible (AWS meetup)
Go Faster with Ansible (AWS meetup)
 
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpecTest-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
Test-Driven Infrastructure with Ansible, Test Kitchen, Serverspec and RSpec
 

Semelhante a Ansible module development 101

Fluo CICD OpenStack Summit
Fluo CICD OpenStack SummitFluo CICD OpenStack Summit
Fluo CICD OpenStack SummitMiguel Zuniga
 
Automated Deployment and Configuration Engines. Ansible
Automated Deployment and Configuration Engines. AnsibleAutomated Deployment and Configuration Engines. Ansible
Automated Deployment and Configuration Engines. AnsibleAlberto Molina Coballes
 
Ansible top 10 - 2018
Ansible top 10 -  2018Ansible top 10 -  2018
Ansible top 10 - 2018Viresh Doshi
 
Quick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developersQuick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developersPaweł Żurowski
 
Mastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMark Wragg
 
Manage your Windows Infrastructure with Puppet Bolt - August 26 - 2020
Manage your Windows Infrastructure with Puppet Bolt - August 26 - 2020Manage your Windows Infrastructure with Puppet Bolt - August 26 - 2020
Manage your Windows Infrastructure with Puppet Bolt - August 26 - 2020Puppet
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)Chris Cowan
 
Code Coverage for Total Security in Application Migrations
Code Coverage for Total Security in Application MigrationsCode Coverage for Total Security in Application Migrations
Code Coverage for Total Security in Application MigrationsDana Luther
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introductionstn_tkiller
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration TestersNikhil Mittal
 
Bootstrapping Puppet and Application Deployment - PuppetConf 2013
Bootstrapping Puppet and Application Deployment - PuppetConf 2013Bootstrapping Puppet and Application Deployment - PuppetConf 2013
Bootstrapping Puppet and Application Deployment - PuppetConf 2013Puppet
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Hannes Lowette
 
Fuzzing Linux Kernel
Fuzzing Linux KernelFuzzing Linux Kernel
Fuzzing Linux KernelPiyush Mishra
 
Build Tools & Maven
Build Tools & MavenBuild Tools & Maven
Build Tools & MavenDavid Simons
 
Driving application development through behavior driven development
Driving application development through behavior driven developmentDriving application development through behavior driven development
Driving application development through behavior driven developmentEinar Ingebrigtsen
 

Semelhante a Ansible module development 101 (20)

Fluo CICD OpenStack Summit
Fluo CICD OpenStack SummitFluo CICD OpenStack Summit
Fluo CICD OpenStack Summit
 
Automated Deployment and Configuration Engines. Ansible
Automated Deployment and Configuration Engines. AnsibleAutomated Deployment and Configuration Engines. Ansible
Automated Deployment and Configuration Engines. Ansible
 
Ansible top 10 - 2018
Ansible top 10 -  2018Ansible top 10 -  2018
Ansible top 10 - 2018
 
Quick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developersQuick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developers
 
Mastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMastering PowerShell Testing with Pester
Mastering PowerShell Testing with Pester
 
Manage your Windows Infrastructure with Puppet Bolt - August 26 - 2020
Manage your Windows Infrastructure with Puppet Bolt - August 26 - 2020Manage your Windows Infrastructure with Puppet Bolt - August 26 - 2020
Manage your Windows Infrastructure with Puppet Bolt - August 26 - 2020
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
CPP03 - Repetition
CPP03 - RepetitionCPP03 - Repetition
CPP03 - Repetition
 
Node.js
Node.jsNode.js
Node.js
 
Code Coverage for Total Security in Application Migrations
Code Coverage for Total Security in Application MigrationsCode Coverage for Total Security in Application Migrations
Code Coverage for Total Security in Application Migrations
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration Testers
 
Bootstrapping Puppet and Application Deployment - PuppetConf 2013
Bootstrapping Puppet and Application Deployment - PuppetConf 2013Bootstrapping Puppet and Application Deployment - PuppetConf 2013
Bootstrapping Puppet and Application Deployment - PuppetConf 2013
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
 
Fuzzing Linux Kernel
Fuzzing Linux KernelFuzzing Linux Kernel
Fuzzing Linux Kernel
 
Build Tools & Maven
Build Tools & MavenBuild Tools & Maven
Build Tools & Maven
 
Top 5 Ansible modules
Top 5 Ansible modulesTop 5 Ansible modules
Top 5 Ansible modules
 
Driving application development through behavior driven development
Driving application development through behavior driven developmentDriving application development through behavior driven development
Driving application development through behavior driven development
 
ansible_rhel.pdf
ansible_rhel.pdfansible_rhel.pdf
ansible_rhel.pdf
 
DevOps for database
DevOps for databaseDevOps for database
DevOps for database
 

Mais de yfauser

Open stack and_vagrant-os-meetup-2015
Open stack and_vagrant-os-meetup-2015Open stack and_vagrant-os-meetup-2015
Open stack and_vagrant-os-meetup-2015yfauser
 
Open stack networking_101_update_2014-os-meetups
Open stack networking_101_update_2014-os-meetupsOpen stack networking_101_update_2014-os-meetups
Open stack networking_101_update_2014-os-meetupsyfauser
 
Open stack networking_101_update_2014
Open stack networking_101_update_2014Open stack networking_101_update_2014
Open stack networking_101_update_2014yfauser
 
Linux Tag 2014 OpenStack Networking
Linux Tag 2014 OpenStack NetworkingLinux Tag 2014 OpenStack Networking
Linux Tag 2014 OpenStack Networkingyfauser
 
Osdc2014 openstack networking yves_fauser
Osdc2014 openstack networking yves_fauserOsdc2014 openstack networking yves_fauser
Osdc2014 openstack networking yves_fauseryfauser
 
Nvp deep dive_session_cee-day
Nvp deep dive_session_cee-dayNvp deep dive_session_cee-day
Nvp deep dive_session_cee-dayyfauser
 
Open stack networking_101_part-2_tech_deep_dive
Open stack networking_101_part-2_tech_deep_diveOpen stack networking_101_part-2_tech_deep_dive
Open stack networking_101_part-2_tech_deep_diveyfauser
 
Open stack networking_101_part-1
Open stack networking_101_part-1Open stack networking_101_part-1
Open stack networking_101_part-1yfauser
 

Mais de yfauser (8)

Open stack and_vagrant-os-meetup-2015
Open stack and_vagrant-os-meetup-2015Open stack and_vagrant-os-meetup-2015
Open stack and_vagrant-os-meetup-2015
 
Open stack networking_101_update_2014-os-meetups
Open stack networking_101_update_2014-os-meetupsOpen stack networking_101_update_2014-os-meetups
Open stack networking_101_update_2014-os-meetups
 
Open stack networking_101_update_2014
Open stack networking_101_update_2014Open stack networking_101_update_2014
Open stack networking_101_update_2014
 
Linux Tag 2014 OpenStack Networking
Linux Tag 2014 OpenStack NetworkingLinux Tag 2014 OpenStack Networking
Linux Tag 2014 OpenStack Networking
 
Osdc2014 openstack networking yves_fauser
Osdc2014 openstack networking yves_fauserOsdc2014 openstack networking yves_fauser
Osdc2014 openstack networking yves_fauser
 
Nvp deep dive_session_cee-day
Nvp deep dive_session_cee-dayNvp deep dive_session_cee-day
Nvp deep dive_session_cee-day
 
Open stack networking_101_part-2_tech_deep_dive
Open stack networking_101_part-2_tech_deep_diveOpen stack networking_101_part-2_tech_deep_dive
Open stack networking_101_part-2_tech_deep_dive
 
Open stack networking_101_part-1
Open stack networking_101_part-1Open stack networking_101_part-1
Open stack networking_101_part-1
 

Último

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 

Último (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

Ansible module development 101

  • 1. © 2014 VMware Inc. All rights reserved.© 2014 VMware Inc. All rights reserved. 22/02/2016 Ansible Module Development 101 Yves Fauser Technical Product Manager @ VMware
  • 2. Who is standing in front of you? • I’m working with VMware’s network virtualization product called NSX • I’m the co-organizer for this Meetup & the OpenStack Munich Meetup group • I’m living in Munich since 14 years • I’ve spend 3 years working at VMware as Systems Engineer & Solution Architect, 7 years as a Systems Engineer at Cisco, and I was a networking / OS consultant and developer before • Topics I love to discuss and work with: Configuration Management, Automation, Containers / ‘Cloud’, OpenStack, Networking, ... Yves Fauser Technical Product Manager @ VMware
  • 3. Why developing your own Modules • There are tons of great build-in core and extra modules for Ansible – So why build your own? • Generally if you only work with Files, Packages and Services on standard OSs you are covered, and there is no need to develop your own stuff • But sometimes you want to do ‘strange stuff’, and then making this idempotent is hard, e.g. • You might want to interact with APIs of products and ‘cloud services’ • You might want to use commands / CLIs that were not build to work well with configuration management (e.g. that don’t implement granular return codes but give you lots of stdout garbage) • I had to do both, interact with an API and use CLI tools with a lot of stdout that I needed to interpret • Working with the VMware NSX API • Using VMware’s OVFTool to deploy VMs into vCenter * * We will show the use the OVFTool Module as an example later
  • 4. Why using Python to develop Modules • Ansible generally supports writing Modules in any language, e.g Python, C, Ruby, Shell, Go, … • The only requirements are: • The language needs to be able to implement File I/O • The language needs to be able write JSON formatted output to STDOUT • Why I am using Python: • First and foremost, I’m a Pythonist – I really like this language • Ansible itself and all its core Modules are written in Python – You have a lot to read and learn from! • There are very easy and ready to use ‘boilerplates’ and ‘helper functions’ for Ansible written for Python • Besides Python, the second most often used language is shell script
  • 5. Getting started – a few important bits of knowledge • When writing a custom module you call it from a Play like this: • Alternatively you can use ‘action’ • In this case ‘test_module’ can be test_module.py, or test_module.sh, test_module.<you_name_it> in the library path • Ansible searches for modules the path specified by ANSIBLE_LIBRARY or the --module-path command line option • The directory ”./library”, alongside your top level playbooks, is also automatically added as a search directory • I personally always use the “./library” option when developing modules
  • 6. Getting started – The ‘boilerplate’ code of every module • You always start with a boilerplate code like this: Uuuhh … that’s ugly, an import statement at the bottom of the file, and importing *, that’s against all python style guides! Why’s that?
  • 7. Ansible code creation • You module code is not the final code that gets executed • Ansible takes the code and constructs a single Python script that gets copied to the remote system and then executed. The statement ‘from ansible.module_utils.basic import *’ imports ~1600 lines of code into this final script
  • 8. Ansible code creation Here’s the place were it inserts the Ansible Module code after your code And the function main() is called right at the end of the code
  • 9. Getting started – The Module argument_spec dictionary mandatory variable mandatory variable, do no log (e.g. passwords) mandatory variable, with fixed possible values optional variable taking any value optional variables checked for existence later variable having a default value variable with a strict type variable with an alias checks if at least one variable in the list is present ensures that only one of two variables are set
  • 10. Getting started – The Module argument_spec dictionary • You can access the modules parameters dictionary with ‘module.params[‘key’]’
  • 11. Exiting the module • Exiting the module is done using ‘module.exit_json’ for successful returns, and ‘module.fail_json’ to fail the task Exit the module with the changed flag set and with additional variables returned to the Play Exit the module successfully, but signaling that there was no change Exit the module with a failure
  • 12. Putting it to work – Example Module • I love to go running, but not when it’s too cold. I will let Ansible decide for me You can find the code here: https://gist.github.com/yfauser/90c0955827c74d83d6a2 If the temperature returned by Open Weather Map in my city is bellow my threshold – I’ll stay at home (keep my current state) If the temperature returned by Open Weather Map in my city is above my threshold – I’ll leave the house (change my state)
  • 13. Putting it to work – The If / Elif / Else way
  • 14. Putting it to work – Catching errors • OK, but what about failed states? Let’s enhance our code a bit Using try/except as well as http status codes as indications of failed conditions
  • 15. Putting it to work – Catching errors  Here we are passing the module to the sub-function to call module.fail_json inside of it
  • 16. Use OS commands with Python based Modules • The python Ansible base code has a great method to interact with the OS • The difference from running this inside of your python based module instead of ‘command’ in your Play is that you can interpret the output returned by the OS command more flexibly • The response object will be a list with two items: • [0] holds the return code of the command as an integer, so you can react based on the return code • [1] holds the stdout of the command as a string – So you can do things like: • Pass it to parsers like ‘json.loads’ to convert it to dictionaries • Search in it with ‘.find’ • Count, sort, pass it through regexp, etc.
  • 17. Use OS commands with Python based Modules • Lets change our example to use OS commands (curl) format the owm url with all mandatory url parameters use the OS command curl to send the request check if curl gave a positive return code check if we received a positive ret. code convert curl stdout to a python dict extract temperature value from dict You can find the code here: https://gist.github.com/yfauser/b2377e ee842a1cd2a899
  • 18. Use OS commands with Python based Modules • Here’s another real life example of using the OS command option • This code uses module.run_command to invoke the ovftool to deploy a VM into vCenter You can find the code here: https://github.com/vmware/nsxansible/blob/master/library/nsx_deploy_ova.py
  • 19. Debugging your module • What is the #1 tool for debugging Python code? => ‘print’ ;-) • Unfortunately sending non-JSON formatted output to stdout will not result in any output on the console when running your Play: • Modules must also not output anything on standard error, because the system will merge standard out with standard error and prevent the JSON from parsing. Capturing standard error and returning it as a variable in the JSON on standard out is fine, and is, in fact, how the command module is implemented • In short => Never use ‘print’
  • 20. Debugging your module code • Instead of printing to stdout, send your debug data into a variable (e.g. a list) and pass it to the module.exit_json or module.fail_json method:
  • 21. What’s this ‘supports_check_mode’ about? • Ansible Playbooks can run in check-mode using the --check option • If ‘supports_check_mode’ is set to: • ‘True’: It’s up to you to make sure your module doesn’t apply changes, but only checks if it would have made changes if Ansible runs in check mode • ‘False’ or unset: The task using your module will be skipped if Ansible runs in check mode
  • 22. Inline Documentation • Ansible supports the generation of module documentation on their Web-Site from inline Documentation in the module code • You can read about all the details here: http://docs.ansible.com/ansible/developing_ modules.html#documenting-your-module
  • 23. Developing Ansible Modules on a MAC • When developing a python based module on a MAC you might run into this: • When you run the module it fails to import libraries because it doesn’t use the right interpreter and path • Solution 1, use the ‘#!/usr/bin/env python’ shebang instead of ‘#!/usr/bin/python’: • Don’t use this! As it’s an anti-pattern if you want to get this into ansible-modules-extra or core  Solution 2, define the interpreter path in the hosts file  This is the proper solution as this solves it on a per host level for those systems that need it
  • 24. Questions? Check out some more of my stuff here: https://github.com/vmware/nsxansible/