SlideShare uma empresa Scribd logo
1 de 26
Baixar para ler offline
Ansible for testing.
How can I use it?
Should I use it?
Scott van Kalken
svk@f5.com
Scott van Kalken
Everyone just calls me “svk” (it’s easier)
I have the privilege of helping run a
few meetups.
Super passionate about open source (not
just software, but data too)
ANSIBLE AND TESTING?!?!?!
Ansible is an awesome toolkit / language to allow you to just get things done.
There are modules and frameworks that allow you to perform testing on roles.
Molecule is one of them.
https://molecule.readthedocs.io/en/stable/
See Rishbah’s fantastic talk on this last time :)
ANSIBLE AND TESTING!?!?!?!
What about if I want to do something other than unit testing?
What are my options?
Can I use Ansible?
Is it a good idea to use Ansible?
...someone recently asked me all of these questions and I didn’t have good answers, so I
decided to explore the topic (and do a talk of course).
ANSIBLE AND TESTING
https://docs.ansible.com/ansible/latest/reference_appendices/test_strategies.html
There’s a whole section in the ansible docs on this.
WHO KNEW!!!!!
THE ASSERT MODULE
https://docs.ansible.com/ansible/latest/modules/assert_module.html
● This module asserts that given expressions are true with an optional
custom message.
● This module is also supported for Windows targets.
I haven’t used it for a windows target but the possibilities are pretty much
endless if you think about it.
THE ASSERT MODULE
- hosts: "{{ target_hosts | default('localhost') }}"
become: yes
become_user: root
vars:
my_param: 10
tasks:
- name: Check my variable
assert:
that:
- my_param <= 100
- my_param >= 0
fail_msg: "'my_param' must be between 0 and 100"
success_msg: "'my_param' is between 0 and 100"
Custom failure and success messages,
these can be set to anything that you
like.
THE ASSERT MODULE
TASK [Check my variable] ********************************
fatal: [localhost]: FAILED! => {
"assertion": "my_param <= 100",
"changed": false,
"evaluated_to": false,
"msg": "'my_param' must be between 0 and 100"
}
TASK [Check my variable] *******************************
ok: [localhost] => {
"changed": false,
"msg": "'my_param' is between 0 and 100"
}
A REAL WORLD EXAMPLE
Let’s see what a real world example looks like.
I have a database, and want to make sure that my playbook has been passed all
of the appropriate variables BEFORE I run a task to configure the database.
THE PLAYBOOK
- hosts: "{{ target_hosts | default('localhost') }}"
become: yes
become_user: root
tasks:
- assert:
that:
- db_host != ''
- db_port != ''
- db_user != ''
- db_user != 'root'
- db_password != ''
- db_name != ''
tags: ['check_vars']
Assertions around variables that are
set.
This can be used in a playbook at the
beginning to check that variables are
set before running something
There is a trick here though.
Can you see it?
THE PLAYBOOK
- hosts: "{{ target_hosts | default('localhost') }}"
become: yes
become_user: root
tasks:
- assert:
that:
- db_host != ''
- db_port != ''
- db_user != ''
- db_user != 'root'
- db_password != ''
- db_name != ''
tags: ['check_vars']
Using the inbuilt tags function of
Ansible, you can run this as a check
before running the playbook.
This is most useful if you are using a
pipeline for deployment!
# ansible-playbook -t check_vars playbook.yml --extra-vars “db_host=foo”
CHECK THAT A FILE EXISTS (ASSERT)
- stat:
path: /path/to/something
register: p
- assert:
that:
- p.stat.exists and p.stat.isdir
You can check that a file exists - but can use a logical AND to stack checks (you
can use logical OR also).
THE WAIT_FOR MODULE
https://docs.ansible.com/ansible/latest/modules/wait_for_module.html
This module waits for a condition to be true before continuing.
- wait_for:
host: "{{ inventory_hostname }}"
port: 22
delegate_to: localhost
- name: Wait for machines to come up completely
wait_for: host={{ item.public_ip }} port=22
with_items: '{{ec2.instances}}'
STANDARD ANSIBLE LOOPS
Don’t forget about standard ansible loops.
Standard ansible loops can be used quite effectively as part of functional
testing if you are waiting for a particular output, or you are waiting for
something to happen.
….and yes because it’s ansible there are a lot of other ways to do this.
STANDARD ANSIBLE LOOPS
A CONTRIVED EXAMPLE:
#!/bin/bash
CFGFILE=a.cfg
if [ -f $CFGFILE ]; then
source $CFGFILE
else
echo "COUNT=0" > $CFGFILE
source $CFGFILE
fi
COUNT=$((COUNT+1))
echo $COUNT
echo "COUNT=$COUNT" > $CFGFILE
Script does nothing but increment its
output by one every time it is run.
First run: 0
Second run: 1
Third run: 2
...and so on.
STANDARD ANSIBLE LOOPS
The playbook uses a standard
loop until the output from the
command is “3”.
The task will try this 10 times
with a delay of five seconds
between each run.
This is useful if you’re waiting
for something to happen.
- hosts: "{{ target_hosts | default('localhost') }}"
become: yes
become_user: root
gather_facts: false
tasks:
- name: Check output of command and stdout
shell: ./a.sh
register: result
until: result.stdout.find("3") != -1
retries: 10
delay: 5
STANDARD ANSIBLE LOOPS
https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#retrying-a-task-until-a-condition-is-met
A real world example - I use this when I build AWX.
- name: Check to ensure AWX has come up successfully - this can take some time.
shell: tower-cli project list
register: result
until: result.stdout.find("Demo Project") != -1
retries: 10
delay: 30
STANDARD ANSIBLE LOOPS
Consider the following example:
● Build Infrastructure
● Install application server
● Wait for application to come up
● Perform functional testing
In this scenario, waiting can be used in combination with assertions to perform
comprehensive functional testing.
ROLLING DEPLOYMENT PATTERNS
You can put all of this together to bring a rolling deployment task with
gated testing to your deployments.
For example:
1) Drop application from load balancer
2) Install new version of application
3) Perform functional testing
4) Add application back to load balancer
Using pre tasks, assertions and post tasks, it is possible to set conditions
on failure such that a bad application deployment is automatically tested
and not added back to your live system.
ROLLING DEPLOYMENT PATTERNS
For the record the next example comes directly from the Ansible
documentation.
ROLLING DEPLOYMENT PATTERNS
- hosts: webservers
pre_tasks:
- name: take out of load balancer pool
command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
roles:
- common
- webserver
- apply_testing_checks
post_tasks:
- name: add back to load balancer pool
command: /usr/bin/add_back_to_pool {{ inventory_hostname }}
COOL - I CAN DO TESTING WITH ANSIBLE
Yes you certainly can.
Functional testing.
Microservice testing.
Expect like functionality (for those who know expect)
...and a whole lot more.
DON’T CONFUSE DECLARATIVE INTENT & TESTING
Don’t confuse ansible’s declarative intent with testing.
A lot of the time, we may test things in a way to pause before carrying on to
another task.
The declarative intent / enforcement of ansible takes care of the initial thing, but
we need to make sure it has finished before we move on.
Other times we will perform functional testing.
DECLARATIVE CONFIGURATION
If you think the service may not be started, the best thing to do is request
it to be started.
- name: Start httpd
systemd:
name: httpd
state: started
If the service fails to start, Ansible will tell you.
FUNCTIONAL TESTING
- name: Fetch Java version
shell: java -version 2>&1 | grep version | awk '{print $3}' | sed 's/"//g'
register: java_version
- assert:
that:
- java_version.stdout | version_compare('1.7', '>=')
The snippet above checks something functional (the version of java), but
it could equally be checking a webservice, or the previous example of
checking that AWX has started correctly.
SO SHOULD I USE ANSIBLE FOR TESTING?
If you want to have a single language for all of your testing needs.
If you want to test the applications that you’ve deployed - then Ansible is
a good fit.
What @svk has seen:
● There is a (large) company in Melbourne who is currently assessing
running their post application testing using ansible.
● You can embed tests into a pipeline.
● You can make the world a better place by using ansible (of course!)

Mais conteúdo relacionado

Mais procurados

A quick intro to Ansible
A quick intro to AnsibleA quick intro to Ansible
A quick intro to AnsibleDan Vaida
 
Ansible Automation to Rule Them All
Ansible Automation to Rule Them AllAnsible Automation to Rule Them All
Ansible Automation to Rule Them AllTim Fairweather
 
Ansible Automation Best Practices From Startups to Enterprises - Minnebar 12
Ansible Automation Best Practices From Startups to Enterprises - Minnebar 12Ansible Automation Best Practices From Startups to Enterprises - Minnebar 12
Ansible Automation Best Practices From Startups to Enterprises - Minnebar 12Keith Resar
 
Network Automation with Ansible
Network Automation with AnsibleNetwork Automation with Ansible
Network Automation with AnsibleAnas
 
Jenkins and ansible reference
Jenkins and ansible referenceJenkins and ansible reference
Jenkins and ansible referencelaonap166
 
Ansible basics workshop
Ansible basics workshopAnsible basics workshop
Ansible basics workshopDavid Karban
 
Docker ansible-make-chef-puppet-unnecessary-minnihan
Docker ansible-make-chef-puppet-unnecessary-minnihanDocker ansible-make-chef-puppet-unnecessary-minnihan
Docker ansible-make-chef-puppet-unnecessary-minnihanjbminn
 
Introduction to Ansible
Introduction to AnsibleIntroduction to Ansible
Introduction to AnsibleCoreStack
 
Infrastructure = Code
Infrastructure = CodeInfrastructure = Code
Infrastructure = CodeGeorg Sorst
 
Monitor-Driven Development Using Ansible
Monitor-Driven Development Using AnsibleMonitor-Driven Development Using Ansible
Monitor-Driven Development Using AnsibleItamar Hassin
 
What Is Ansible? | How Ansible Works? | Ansible Tutorial For Beginners | DevO...
What Is Ansible? | How Ansible Works? | Ansible Tutorial For Beginners | DevO...What Is Ansible? | How Ansible Works? | Ansible Tutorial For Beginners | DevO...
What Is Ansible? | How Ansible Works? | Ansible Tutorial For Beginners | DevO...Simplilearn
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentationSuresh Kumar
 
Vagrant, Ansible, and OpenStack on your laptop
Vagrant, Ansible, and OpenStack on your laptopVagrant, Ansible, and OpenStack on your laptop
Vagrant, Ansible, and OpenStack on your laptopLorin Hochstein
 
Deploying PHP Applications with Ansible
Deploying PHP Applications with AnsibleDeploying PHP Applications with Ansible
Deploying PHP Applications with AnsibleOrestes Carracedo
 
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)

A quick intro to Ansible
A quick intro to AnsibleA quick intro to Ansible
A quick intro to Ansible
 
Introducing Ansible
Introducing AnsibleIntroducing Ansible
Introducing Ansible
 
Ansible Automation to Rule Them All
Ansible Automation to Rule Them AllAnsible Automation to Rule Them All
Ansible Automation to Rule Them All
 
Ansible Automation Best Practices From Startups to Enterprises - Minnebar 12
Ansible Automation Best Practices From Startups to Enterprises - Minnebar 12Ansible Automation Best Practices From Startups to Enterprises - Minnebar 12
Ansible Automation Best Practices From Startups to Enterprises - Minnebar 12
 
Network Automation with Ansible
Network Automation with AnsibleNetwork Automation with Ansible
Network Automation with Ansible
 
Jenkins and ansible reference
Jenkins and ansible referenceJenkins and ansible reference
Jenkins and ansible reference
 
Ansible
AnsibleAnsible
Ansible
 
Ansible basics workshop
Ansible basics workshopAnsible basics workshop
Ansible basics workshop
 
infra-as-code
infra-as-codeinfra-as-code
infra-as-code
 
Ansible
AnsibleAnsible
Ansible
 
Docker ansible-make-chef-puppet-unnecessary-minnihan
Docker ansible-make-chef-puppet-unnecessary-minnihanDocker ansible-make-chef-puppet-unnecessary-minnihan
Docker ansible-make-chef-puppet-unnecessary-minnihan
 
Introduction to Ansible
Introduction to AnsibleIntroduction to Ansible
Introduction to Ansible
 
Infrastructure = Code
Infrastructure = CodeInfrastructure = Code
Infrastructure = Code
 
Monitor-Driven Development Using Ansible
Monitor-Driven Development Using AnsibleMonitor-Driven Development Using Ansible
Monitor-Driven Development Using Ansible
 
What Is Ansible? | How Ansible Works? | Ansible Tutorial For Beginners | DevO...
What Is Ansible? | How Ansible Works? | Ansible Tutorial For Beginners | DevO...What Is Ansible? | How Ansible Works? | Ansible Tutorial For Beginners | DevO...
What Is Ansible? | How Ansible Works? | Ansible Tutorial For Beginners | DevO...
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
 
Vagrant, Ansible, and OpenStack on your laptop
Vagrant, Ansible, and OpenStack on your laptopVagrant, Ansible, and OpenStack on your laptop
Vagrant, Ansible, and OpenStack on your laptop
 
Cyansible
CyansibleCyansible
Cyansible
 
Deploying PHP Applications with Ansible
Deploying PHP Applications with AnsibleDeploying PHP Applications with Ansible
Deploying PHP Applications with Ansible
 
Testing Ansible with Jenkins and Docker
Testing Ansible with Jenkins and DockerTesting Ansible with Jenkins and Docker
Testing Ansible with Jenkins and Docker
 

Semelhante a Ansible testing

utPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLutPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLSteven Feuerstein
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciollaAndrea Paciolla
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It'sJim Lynch
 
Nagios Conference 2011 - Nathan Vonnahme - Integrating Nagios With Test Drive...
Nagios Conference 2011 - Nathan Vonnahme - Integrating Nagios With Test Drive...Nagios Conference 2011 - Nathan Vonnahme - Integrating Nagios With Test Drive...
Nagios Conference 2011 - Nathan Vonnahme - Integrating Nagios With Test Drive...Nagios
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSKnoldus Inc.
 
Running and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test FrameworkRunning and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test Frameworkwebhostingguy
 
Ansible with oci
Ansible with ociAnsible with oci
Ansible with ociDonghuKIM2
 
Mastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMark Wragg
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Ansible Devops North East - slides
Ansible Devops North East - slides Ansible Devops North East - slides
Ansible Devops North East - slides InfinityPP
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Knowvilniusjug
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017Ortus Solutions, Corp
 
Ansible, integration testing, and you.
Ansible, integration testing, and you.Ansible, integration testing, and you.
Ansible, integration testing, and you.Bob Killen
 
Unit testing for WordPress
Unit testing for WordPressUnit testing for WordPress
Unit testing for WordPressHarshad Mane
 
Testing for software engineers
Testing for software engineersTesting for software engineers
Testing for software engineersMohammed Ashour
 

Semelhante a Ansible testing (20)

utPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLutPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQL
 
Testing Ansible
Testing AnsibleTesting Ansible
Testing Ansible
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
Unit Testing Lots of Perl
Unit Testing Lots of PerlUnit Testing Lots of Perl
Unit Testing Lots of Perl
 
Nagios Conference 2011 - Nathan Vonnahme - Integrating Nagios With Test Drive...
Nagios Conference 2011 - Nathan Vonnahme - Integrating Nagios With Test Drive...Nagios Conference 2011 - Nathan Vonnahme - Integrating Nagios With Test Drive...
Nagios Conference 2011 - Nathan Vonnahme - Integrating Nagios With Test Drive...
 
Database Management Assignment Help
Database Management Assignment Help Database Management Assignment Help
Database Management Assignment Help
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 
Running and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test FrameworkRunning and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test Framework
 
Ansible with oci
Ansible with ociAnsible with oci
Ansible with oci
 
Mastering PowerShell Testing with Pester
Mastering PowerShell Testing with PesterMastering PowerShell Testing with Pester
Mastering PowerShell Testing with Pester
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Ansible Devops North East - slides
Ansible Devops North East - slides Ansible Devops North East - slides
Ansible Devops North East - slides
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
 
Ansible, integration testing, and you.
Ansible, integration testing, and you.Ansible, integration testing, and you.
Ansible, integration testing, and you.
 
Unit testing for WordPress
Unit testing for WordPressUnit testing for WordPress
Unit testing for WordPress
 
Testing for software engineers
Testing for software engineersTesting for software engineers
Testing for software engineers
 

Último

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 

Último (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Ansible testing

  • 1. Ansible for testing. How can I use it? Should I use it? Scott van Kalken svk@f5.com
  • 2. Scott van Kalken Everyone just calls me “svk” (it’s easier) I have the privilege of helping run a few meetups. Super passionate about open source (not just software, but data too)
  • 3. ANSIBLE AND TESTING?!?!?! Ansible is an awesome toolkit / language to allow you to just get things done. There are modules and frameworks that allow you to perform testing on roles. Molecule is one of them. https://molecule.readthedocs.io/en/stable/ See Rishbah’s fantastic talk on this last time :)
  • 4. ANSIBLE AND TESTING!?!?!?! What about if I want to do something other than unit testing? What are my options? Can I use Ansible? Is it a good idea to use Ansible? ...someone recently asked me all of these questions and I didn’t have good answers, so I decided to explore the topic (and do a talk of course).
  • 6. THE ASSERT MODULE https://docs.ansible.com/ansible/latest/modules/assert_module.html ● This module asserts that given expressions are true with an optional custom message. ● This module is also supported for Windows targets. I haven’t used it for a windows target but the possibilities are pretty much endless if you think about it.
  • 7. THE ASSERT MODULE - hosts: "{{ target_hosts | default('localhost') }}" become: yes become_user: root vars: my_param: 10 tasks: - name: Check my variable assert: that: - my_param <= 100 - my_param >= 0 fail_msg: "'my_param' must be between 0 and 100" success_msg: "'my_param' is between 0 and 100" Custom failure and success messages, these can be set to anything that you like.
  • 8. THE ASSERT MODULE TASK [Check my variable] ******************************** fatal: [localhost]: FAILED! => { "assertion": "my_param <= 100", "changed": false, "evaluated_to": false, "msg": "'my_param' must be between 0 and 100" } TASK [Check my variable] ******************************* ok: [localhost] => { "changed": false, "msg": "'my_param' is between 0 and 100" }
  • 9. A REAL WORLD EXAMPLE Let’s see what a real world example looks like. I have a database, and want to make sure that my playbook has been passed all of the appropriate variables BEFORE I run a task to configure the database.
  • 10. THE PLAYBOOK - hosts: "{{ target_hosts | default('localhost') }}" become: yes become_user: root tasks: - assert: that: - db_host != '' - db_port != '' - db_user != '' - db_user != 'root' - db_password != '' - db_name != '' tags: ['check_vars'] Assertions around variables that are set. This can be used in a playbook at the beginning to check that variables are set before running something There is a trick here though. Can you see it?
  • 11. THE PLAYBOOK - hosts: "{{ target_hosts | default('localhost') }}" become: yes become_user: root tasks: - assert: that: - db_host != '' - db_port != '' - db_user != '' - db_user != 'root' - db_password != '' - db_name != '' tags: ['check_vars'] Using the inbuilt tags function of Ansible, you can run this as a check before running the playbook. This is most useful if you are using a pipeline for deployment! # ansible-playbook -t check_vars playbook.yml --extra-vars “db_host=foo”
  • 12. CHECK THAT A FILE EXISTS (ASSERT) - stat: path: /path/to/something register: p - assert: that: - p.stat.exists and p.stat.isdir You can check that a file exists - but can use a logical AND to stack checks (you can use logical OR also).
  • 13. THE WAIT_FOR MODULE https://docs.ansible.com/ansible/latest/modules/wait_for_module.html This module waits for a condition to be true before continuing. - wait_for: host: "{{ inventory_hostname }}" port: 22 delegate_to: localhost - name: Wait for machines to come up completely wait_for: host={{ item.public_ip }} port=22 with_items: '{{ec2.instances}}'
  • 14. STANDARD ANSIBLE LOOPS Don’t forget about standard ansible loops. Standard ansible loops can be used quite effectively as part of functional testing if you are waiting for a particular output, or you are waiting for something to happen. ….and yes because it’s ansible there are a lot of other ways to do this.
  • 15. STANDARD ANSIBLE LOOPS A CONTRIVED EXAMPLE: #!/bin/bash CFGFILE=a.cfg if [ -f $CFGFILE ]; then source $CFGFILE else echo "COUNT=0" > $CFGFILE source $CFGFILE fi COUNT=$((COUNT+1)) echo $COUNT echo "COUNT=$COUNT" > $CFGFILE Script does nothing but increment its output by one every time it is run. First run: 0 Second run: 1 Third run: 2 ...and so on.
  • 16. STANDARD ANSIBLE LOOPS The playbook uses a standard loop until the output from the command is “3”. The task will try this 10 times with a delay of five seconds between each run. This is useful if you’re waiting for something to happen. - hosts: "{{ target_hosts | default('localhost') }}" become: yes become_user: root gather_facts: false tasks: - name: Check output of command and stdout shell: ./a.sh register: result until: result.stdout.find("3") != -1 retries: 10 delay: 5
  • 17. STANDARD ANSIBLE LOOPS https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#retrying-a-task-until-a-condition-is-met A real world example - I use this when I build AWX. - name: Check to ensure AWX has come up successfully - this can take some time. shell: tower-cli project list register: result until: result.stdout.find("Demo Project") != -1 retries: 10 delay: 30
  • 18. STANDARD ANSIBLE LOOPS Consider the following example: ● Build Infrastructure ● Install application server ● Wait for application to come up ● Perform functional testing In this scenario, waiting can be used in combination with assertions to perform comprehensive functional testing.
  • 19. ROLLING DEPLOYMENT PATTERNS You can put all of this together to bring a rolling deployment task with gated testing to your deployments. For example: 1) Drop application from load balancer 2) Install new version of application 3) Perform functional testing 4) Add application back to load balancer Using pre tasks, assertions and post tasks, it is possible to set conditions on failure such that a bad application deployment is automatically tested and not added back to your live system.
  • 20. ROLLING DEPLOYMENT PATTERNS For the record the next example comes directly from the Ansible documentation.
  • 21. ROLLING DEPLOYMENT PATTERNS - hosts: webservers pre_tasks: - name: take out of load balancer pool command: /usr/bin/take_out_of_pool {{ inventory_hostname }} roles: - common - webserver - apply_testing_checks post_tasks: - name: add back to load balancer pool command: /usr/bin/add_back_to_pool {{ inventory_hostname }}
  • 22. COOL - I CAN DO TESTING WITH ANSIBLE Yes you certainly can. Functional testing. Microservice testing. Expect like functionality (for those who know expect) ...and a whole lot more.
  • 23. DON’T CONFUSE DECLARATIVE INTENT & TESTING Don’t confuse ansible’s declarative intent with testing. A lot of the time, we may test things in a way to pause before carrying on to another task. The declarative intent / enforcement of ansible takes care of the initial thing, but we need to make sure it has finished before we move on. Other times we will perform functional testing.
  • 24. DECLARATIVE CONFIGURATION If you think the service may not be started, the best thing to do is request it to be started. - name: Start httpd systemd: name: httpd state: started If the service fails to start, Ansible will tell you.
  • 25. FUNCTIONAL TESTING - name: Fetch Java version shell: java -version 2>&1 | grep version | awk '{print $3}' | sed 's/"//g' register: java_version - assert: that: - java_version.stdout | version_compare('1.7', '>=') The snippet above checks something functional (the version of java), but it could equally be checking a webservice, or the previous example of checking that AWX has started correctly.
  • 26. SO SHOULD I USE ANSIBLE FOR TESTING? If you want to have a single language for all of your testing needs. If you want to test the applications that you’ve deployed - then Ansible is a good fit. What @svk has seen: ● There is a (large) company in Melbourne who is currently assessing running their post application testing using ansible. ● You can embed tests into a pipeline. ● You can make the world a better place by using ansible (of course!)