Ansible Playbook Essentials
By Gourav Shah
()
About this ebook
Design automation blueprints using Ansible's playbooks to orchestrate and manage your multi-tier infrastructure
About This Book- Get to grips with Ansible's features such as orchestration, automatic node discovery, and data encryption
- Create data-driven, modular and reusable automation code with Ansible roles, facts, variables, and templates
- A step-by-step approach to automating and managing system and application configurations effectively using Ansible's playbooks
If you are a systems or automation engineer who intends to automate common infrastructure tasks, deploy applications, and use orchestration to configure systems in a co-ordinated manner, then this book is for you. Some understanding of the Linux/UNIX command line interface is expected.
What You Will Learn- Write simple tasks and plays
- Organize code into a reusable, modular structure
- Separate code from data using variables and Jinja2 templates
- Run custom commands and scripts using Ansible's command modules
- Control execution flow based on conditionals
- Integrate nodes and discover topology information about other nodes in the cluster
- Encrypt data with ansible-vault
- Create environments with isolated configurations to match application development workflow
- Orchestrate infrastructure and deploy applications in a coordinated manner
Ansible combines configuration management, orchestration, and parallel command execution into a single tool. Its batteries-included approach and built-in module library makes it easy to integrate it with cloud platforms, databases, and notification services without requiring additional plugins. Playbooks in Ansible define the policies your systems under management enforce. They facilitate effective configuration management rather than running ad hoc scripts to deploy complex applications.
This book will show you how to write a blueprint of your infrastructure encompassing multi-tier applications using Ansible's playbooks. Beginning with the basic concepts such as plays, tasks, handlers, inventory, and the YAML syntax that Ansible uses, you will see how to organize your code into a modular structure. Building on this, you will master techniques to create data-driven playbooks with variables, templates, logical constructs, and encrypted data. This book will also take you through advanced clustering concepts such as discovering topology information, managing multiple environments, and orchestration.
By the end of this book, you will be able to design solutions to your automation and orchestration problems using playbooks quickly and efficiently.
Style and approachThis book follows a step-by-step approach, with the concepts explained in a conversational and easy-to-follow style. Each topic is explained sequentially in the process of creating a course. A comprehensive explanation of the basic and advanced features of Ansible playbooks is also included.
Gourav Shah
Gourav Shah (www.gouravshah.com) has extensive experience in building and managing highly available, automated, fault-tolerant infrastructure and scaling it. He started his career as a passionate Linux and open source enthusiast, transformed himself into an operations engineer, and evolved to be a cloud and DevOps expert and trainer. In his previous avatar, Gourav headed IT operations for Efficient Frontier (now Adobe), India. He founded Initcron Systems (www.initcron.com), a niche consulting firm that specializes in DevOps enablement and cloud infrastructure management. Under the Initcron banner, he helps companies design DevOps strategies and helps implement them. Initcron also provides automation services for start-ups, as well as large enterprises. Gourav is a coveted corporate trainer and has trained professionals from top IT companies around the world, such as IBM, CISCO, Qualcomm, Accenture, Dreamworks, Walmart Labs, Intuit, and Wells Fargo, to name a few. He runs a specialized training school by the name School of Devops (www.schoolofdevops.com) to groom world class cloud and DevOps professionals.
Related to Ansible Playbook Essentials
Related ebooks
Mastering Ansible Rating: 5 out of 5 stars5/5Mastering Ansible - Second Edition Rating: 0 out of 5 stars0 ratingsNginx Essentials Rating: 0 out of 5 stars0 ratingsMastering NGINX - Second Edition Rating: 0 out of 5 stars0 ratingsPractical DevOps Rating: 3 out of 5 stars3/5CentOS System Administration Essentials Rating: 0 out of 5 stars0 ratingsImplementing DevOps on AWS Rating: 0 out of 5 stars0 ratingsOpenStack Administration with Ansible 2 - Second Edition Rating: 0 out of 5 stars0 ratingsVagrant Virtual Development Environment Cookbook Rating: 5 out of 5 stars5/5Mastering Linux Shell Scripting Rating: 4 out of 5 stars4/5OpenStack Administration with Ansible Rating: 0 out of 5 stars0 ratingsImplementing DevOps with Microsoft Azure Rating: 0 out of 5 stars0 ratingsDevOps for Web Development Rating: 0 out of 5 stars0 ratingsHyper-V 2016 Best Practices Rating: 0 out of 5 stars0 ratingsLearning Ansible 2 - Second Edition Rating: 5 out of 5 stars5/5Docker: A Quick-Start Beginner's Guide Rating: 4 out of 5 stars4/5Learning Docker Rating: 5 out of 5 stars5/5Getting Started with Kubernetes - Second Edition Rating: 0 out of 5 stars0 ratingsInfrastructure as Code (IAC) Cookbook Rating: 0 out of 5 stars0 ratingsDevOps for Networking Rating: 0 out of 5 stars0 ratingsLearning Docker - Second Edition Rating: 0 out of 5 stars0 ratingsDocker Demystified: Learn How to Develop and Deploy Applications Using Docker (English Edition) Rating: 0 out of 5 stars0 ratingsLearn Kubernetes - Container orchestration using Docker: Learn Collection Rating: 4 out of 5 stars4/5Learn Docker in a Month of Lunches Rating: 0 out of 5 stars0 ratingsAnsible for IT Experts Rating: 0 out of 5 stars0 ratingsLearn Kubernetes & Docker - .NET Core, Java, Node.JS, PHP or Python Rating: 0 out of 5 stars0 ratingsMastering Kubernetes Rating: 5 out of 5 stars5/5Kubernetes Handbook: Non-Programmer's Guide to Deploy Applications with Kubernetes Rating: 4 out of 5 stars4/5Hands-On Microservices with Kubernetes: Build, deploy, and manage scalable microservices on Kubernetes Rating: 5 out of 5 stars5/5Linux Networking Cookbook Rating: 0 out of 5 stars0 ratings
Networking For You
Networking All-in-One For Dummies Rating: 5 out of 5 stars5/5Networking For Dummies Rating: 5 out of 5 stars5/5Quantum Computing For Dummies Rating: 0 out of 5 stars0 ratingsLinux Bible Rating: 0 out of 5 stars0 ratingsPractical Ethical Hacking from Scratch Rating: 5 out of 5 stars5/5Hacking Android Rating: 4 out of 5 stars4/5The Compete Ccna 200-301 Study Guide: Network Engineering Edition Rating: 5 out of 5 stars5/5AWS Certified Cloud Practitioner Study Guide: CLF-C01 Exam Rating: 5 out of 5 stars5/5TCP/IP for Everyone Rating: 4 out of 5 stars4/5AWS Certified Solutions Architect Study Guide: Associate SAA-C02 Exam Rating: 0 out of 5 stars0 ratingsSharePoint For Dummies Rating: 0 out of 5 stars0 ratingsAmazon Web Services (AWS) Interview Questions and Answers Rating: 5 out of 5 stars5/5Cisco Networking All-in-One For Dummies Rating: 4 out of 5 stars4/5Microsoft Certified Azure Fundamentals Study Guide: Exam AZ-900 Rating: 0 out of 5 stars0 ratingsCisco CCNA Command Guide: An Introductory Guide for CCNA & Computer Networking Beginners: Computer Networking, #3 Rating: 0 out of 5 stars0 ratingsThe Windows Command Line Beginner's Guide: Second Edition Rating: 4 out of 5 stars4/5CompTIA Network+ Practice Tests: Exam N10-008 Rating: 0 out of 5 stars0 ratingsMike Meyers' CompTIA Network+ Certification Passport, Sixth Edition (Exam N10-007) Rating: 1 out of 5 stars1/5CCNA Certification Study Guide, Volume 2: Exam 200-301 Rating: 0 out of 5 stars0 ratingsA Beginner's Guide to Ham Radio Rating: 0 out of 5 stars0 ratingsRaspberry Pi Electronics Projects for the Evil Genius Rating: 3 out of 5 stars3/5A Practical Guide Wireshark Forensics Rating: 5 out of 5 stars5/5Windows Command Line Administration Instant Reference Rating: 0 out of 5 stars0 ratingsArtificial Intelligence for Fashion: How AI is Revolutionizing the Fashion Industry Rating: 0 out of 5 stars0 ratingsMicrosoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsNetwork+ Study Guide & Practice Exams Rating: 4 out of 5 stars4/5IPv6: Theory, Protocol, and Practice Rating: 5 out of 5 stars5/5Cybersecurity: The Beginner's Guide: A comprehensive guide to getting started in cybersecurity Rating: 5 out of 5 stars5/5
Reviews for Ansible Playbook Essentials
0 ratings0 reviews
Book preview
Ansible Playbook Essentials - Gourav Shah
Table of Contents
Ansible Playbook Essentials
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
Setting Up the Learning Environment
Understanding the learning environment
Prerequisites
Systems prerequisites
The base software
Creating virtual machines
Installing Ansible on the controller
Using sample code
1. Blueprinting Your Infrastructure
Getting introduced to Ansible
Plays
YAML – the playbook language
Our first playbook
Creating a host inventory
Patterns
Tasks
Modules
The modules and idempotence
Running the playbook
Review questions
Summary
2. Going Modular with Ansible Roles
Understanding roles
Naming roles
The directory layout for roles
Creating a site-wide playbook, nesting, and using include statements
Creating the www playbook
The default and custom role paths
Parameterizing the roles
Creating a base role
Refactoring our code – creating a base role
Creating an Nginx role
Adding role dependencies
Managing files for Nginx
Automating events and actions with handlers
Adding pre-tasks and post-tasks to playbooks
Running playbooks with roles
Review questions
Summary
3. Separating Code and Data – Variables, Facts, and Templates
Static content explosion
Separating code and data
Jinja2 templates
The template formation
Facts and variables
Automatic variables – facts
User-defined variables
Where to define a variable
How to define a variable
Templating the Nginx configurations
Adding another layer – the MySQL role
Creating the scaffolding for the roles with Ansible-Galaxy
Adding metadata to the role
Using variables in tasks and handlers
Creating variables
Creating tasks
Using variables in playbooks
Applying a MySQL role to the DB servers
Variable precedence
The best practices for variable usage
Review questions
Summary
4. Bringing In Your Code – Custom Commands and Scripts
The command modules
Using the raw module
Using the command module
Using the shell module
Using the script module
Deploying a WordPress application – a hands-on approach
Installing WordPress
Controlling the idempotence of command modules
The registered variables
Extracting WordPress with a shell module
Configuring WordPress
Review questions
Summary
5. Controlling Execution Flow – Conditionals
The conditional control structure
The when statements
Fact-based selection
Refactoring the MySQL role
Multilevel variable dictionaries
Merging hashes
Configuring the MySQL server selectively
Conditional control structure in Jinja2 templates
Updating the MySQL template
Running a task only once
Executing roles conditionally
Review questions
Summary
6. Iterative Control Structures – Loops
The omnipotent with statement
Configuring WordPress requisites
The PHP5-FPM role
Defining an array
Looping an array
Creating MySQL databases and user accounts
Creating a hash
Nested hashes
Iterating a hash
Creating Nginx virtual hosts
Defining the PHP site information
Review questions
Summary
7. Node Discovery and Clustering
Node discovery with magic variables
Creating the load balancer role
Accessing facts for non-playbook hosts
Facts caching with Redis
Caching facts in files
Review questions
Summary
8. Encrypting Data with Vault
Ansible-vault
Advanced Encryption Standard
What to encrypt with the vault?
Using the Ansible-vault
Encrypting the data
Updating the encrypted data
Rotating the encryption keys
Encrypting the database credentials
Using a password file
Adding the vault password file option to the Ansible configuration
Using encrypted data in templates
Adding SSL support to Nginx
Review questions
Summary
9. Managing Environments
Approaches for managing environments
The inventory groups and variables
Approach 1 – using nested groups in an inventory
Approach 2 – using environment-specific inventory variables
Creating a development environment
Review questions
Summary
10. Orchestrating Infrastructure with Ansible
Ansible as an orchestrator
Multiple playbooks and ordering
Pre-tasks and post-tasks
Delegation
Rolling updates
Tests
Tags
Patterns and limits
Tagging the roles
Creating an orchestration playbook for WordPress
Review questions
Summary
A. References
Index
Ansible Playbook Essentials
Ansible Playbook Essentials
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: August 2015
Production reference: 1290715
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78439-829-3
www.packtpub.com
Credits
Author
Gourav Shah
Reviewers
Ajey Gore
Olivier Korver
Ben Mildren
Aditya Patawari
Acquisition Editor
Vinay Argekar
Content Development Editor
Amey Varangaonkar
Technical Editor
Abhishek R. Kotian
Copy Editors
Pranjali Chury
Neha Vyas
Project Coordinator
Suzanne Coutinho
Proofreader
Safis Editing
Indexer
Monica Ajmera Mehta
Graphics
Jason Monteiro
Production Coordinator
Nilesh R. Mohite
Cover Work
Nilesh R. Mohite
About the Author
Gourav Shah (www.gouravshah.com) has extensive experience in building and managing highly available, automated, fault-tolerant infrastructure and scaling it. He started his career as a passionate Linux and open source enthusiast, transformed himself into an operations engineer, and evolved to be a cloud and DevOps expert and trainer.
In his previous avatar, Gourav headed IT operations for Efficient Frontier (now Adobe), India. He founded Initcron Systems (www.initcron.com), a niche consulting firm that specializes in DevOps enablement and cloud infrastructure management. Under the Initcron banner, he helps companies design DevOps strategies and helps implement them. Initcron also provides automation services for start-ups, as well as large enterprises.
Gourav is a coveted corporate trainer and has trained professionals from top IT companies around the world, such as IBM, CISCO, Qualcomm, Accenture, Dreamworks, Walmart Labs, Intuit, and Wells Fargo, to name a few. He runs a specialized training school by the name School of Devops (www.schoolofdevops.com) to groom world class cloud and DevOps professionals.
Acknowledgments
My journey to becoming a DevOps expert, a trainer, an entrepreneur, and with this book, an author, is full of interesting stories, people, and experiences. The seeds for my professional expertise were sown during my engineering days, when I was introduced to the open, friendly, and limitless world of free software by evangelists such as Trevor Warren, Dinesh Shah, and Dr. Nagarjuna G, with support and encouragement of a few seniors, especially Gurpreet Singh. I took Linux as a passion and quickly became the point man for any queries on computer networks and Linux.
I feel extremely fortunate to have converted my passion into a profession. My long stint at Efficient Frontier (now Adobe) has been the cornerstone of my technical foundation. It was an ocean of knowledge with great minds at work. I am honored to have worked alongside and learn from experts, namely Harold Barker, Alex Eulenberg, David Gould, and Anand Ranganathan, from whom I learned various aspects of IT Operational practices. I would like to thank Vikram Vijayaraghavan, Harold Sasaki, and Mohan Gopalakrishanan, who truly empowered me and showed me how to lead. I would also like to thank Ashok and Dennis for being great teammates.
I am deeply indebted to Michael DeHaan, the creator of the Ansible project, and the community members who have contributed toward developing, implementing, documenting, and evangelizing such a fantastic product, that is, Ansible. Without their efforts, this book would have been impossible.
I would like to thank the editing, publishing, and reviewing teams, especially Amey Varangaonkar, Abhishek Kotian, and Vinay Argekar, with whom I have been interacting, and the numerous other contributors working behind the scenes. Thank you for being extremely patient and flexible, accommodating my busy schedules, bringing me back on track, and helping me through the process toward the completion of this book. The job of reviewers is not easy. I especially thank Oliver, Ajey, Aditya, and Ben for thoroughly reviewing my work and coming up with invaluable suggestions that contributed toward improving the quality of this book significantly.
Most importantly, I would like to mention my family, which includes my parents, Rajul and Jawahar; my wife, Khushboo; my sister, Swarada; and my brother-in-law, Mayuresh, who have stood by me through thick and thin and love me unconditionally. I must thank Khushboo, my loving wife, who has supported me in all my ventures.
I dedicate this book to my father, Dr. Jawahar Shah, the most positive person I have ever met in my life, who bravely fought the battle against a formidable foe, ALS, and survived. You are my hero, Pappa!
About the Reviewers
Ajey Gore has more than 18 years of work experience in core technology strategy, research and development, and consulting. He has advised others on as well as built better business technologies for various clients across the globe while serving as the head of technology for ThoughtWorks, India.
He founded CodeIgnition (http://codeignition.co), a boutique DevOps and infrastructure automation firm in 2013, where he serves as the chief executive officer and principal technology consultant. Since 2013, the company has grown to 30 people. This company serves start-ups and helps them grow their business without worrying about infrastructure or scaling issues.
He is passionate about infrastructure automation, continuous delivery, the DevOps culture and tools, cloud infrastructure orchestration, virtualization strategies and hybrid cloud implementations, and networks and security. He speaks at various conferences and meetups and writes about different subjects on his website at http://ajeygore.in.
Since 2010, Ajey has helped to run RubyConf India, DevOpsDays India, and RailsGirls India. He is part of the Emerging Technologies Trust, a nonprofit organization responsible for running conferences, and is also committed to promoting technology in India.
Olivier Korver has been a Linux Sysadmin for over 5 years and has a passion for automation. His motto is that any repetitive task can and should be automated. Therefore, not only does he code his own middleware and OS stack in Ansible or Puppet, but he also assists developers in greatly improving their workflow by showing them how it takes very little time to set up Ansible, Docker, and Puppet and also learn the tools provided by them.
Aditya Patawari is a systems engineer by profession and just loves to play around with Linux and other open source technologies. He works on various parts of system life cycles and handles infrastructure automation and the scaling of applications. He is also a contributor