Docsity

ansible for devops for begginner, Teses (TCC) de Informática

Pré-visualização parcial do texto

Baixe ansible for devops for begginner e outras Teses (TCC) em PDF para Informática, somente na Docsity!

Ansible for DevOps

Server and configuration management for

humans

Jeff Geerling

This book is for sale at http://leanpub.com/ansible-for-devops

This version was published on 2016-09-

ISBN 978-0-9863934-0-

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do.

© 2014 - 2016 Jeff Geerling

This book is dedicated to my wife, Natalie, and my children.

Editing by Margie Newman and Katherine Geerling.

Cover photograph and illustration © 2011 Jeff Geerling.

Ansible is a software product distributed under the GNU GPLv3 open source license.

Contents

Foreword..................................... i

Preface...................................... iii Who is this book for?............................ iv Typographic conventions.......................... iv Please help improve this book!....................... v About the Author.............................. vi

Introduction................................... vii In the beginning, there were sysadmins.................. vii Modern infrastructure management.................... vii Ansible and Ansible, Inc........................... viii Ansible Examples.............................. x Other resources............................... x

Chapter 1 - Getting Started with Ansible................... 1 Ansible and Infrastructure Management.................. 1 On snowflakes and shell scripts..................... 1 Configuration management....................... 2 Installing Ansible.............................. 3 Creating a basic inventory file....................... 6 Running your first Ad-Hoc Ansible command............... 7 Summary................................... 8

Chapter 2 - Local Infrastructure Development: Ansible and Vagrant... 9 Prototyping and testing with local virtual machines............ 9 Your first local server: Setting up Vagrant................. 10

  • Using Ansible with Vagrant
  • Your first Ansible playbook
  • Cleaning Up
  • Summary
  • Chapter 3 - Ad-Hoc Commands
    • Conducting an orchestra
    • Build infrastructure with Vagrant for testing
    • Inventory file for multiple servers
    • Your first ad-hoc commands
      • Discover Ansible’s parallel nature
      • Learning about your environment
      • Make changes using Ansible modules
    • Configure groups of servers, or individual servers
      • Configure the Application servers
      • Configure the Database servers
      • Make changes to just one server
    • Manage users and groups
    • Manage packages
    • Manage files and directories
      • Get information about a file
      • Copy a file to the servers
      • Retrieve a file from the servers
      • Create directories and files
      • Delete directories and files
    • Run operations in the background
      • Update servers asynchronously, monitoring progress
      • Fire-and-forget tasks
    • Check log files
    • Manage cron jobs
    • Deploy a version-controlled application
    • Ansible’s SSH connection history
      • Paramiko
      • OpenSSH (default)
      • Accelerated Mode
      • Faster OpenSSH in Ansible 1.5+
    • Summary CONTENTS
  • Chapter 4 - Ansible Playbooks
    • Power plays
    • Running Playbooks with ansible-playbook
      • Limiting playbooks to particular hosts and groups
      • Setting user and sudo options with ansible-playbook
      • Other options for ansible-playbook
    • Real-world playbook: CentOS Node.js app server
      • Add extra repositories
      • Deploy a Node.js app
      • Launch a Node.js app
      • Node.js app server summary
    • Real-world playbook: Ubuntu LAMP server with Drupal
      • Include a variables file, and discover pre_tasks and handlers
      • Basic LAMP server setup
      • Configure Apache
      • Configure PHP with lineinfile
      • Configure MySQL
      • Install Composer and Drush
      • Install Drupal with Git and Drush
      • Drupal LAMP server summary
    • Real-world playbook: Ubuntu server with Solr
      • Include a variables file, and more pre_tasks and handlers
      • Install Java
      • Install Apache Solr
      • Apache Solr server summary
    • Summary
  • Chapter 5 - Ansible Playbooks - Beyond the Basics
    • Handlers
    • Environment variables
      • Per-play environment variables
    • Variables
      • Playbook Variables
      • Inventory variables
      • Registered Variables CONTENTS
      • Accessing Variables
      • Host and Group variables
        • Automatically-loaded group_vars and host_vars
        • Magic variables with host and group variables and information
      • Facts (Variables derived from system information)
        • Local Facts (Facts.d)
      • Ansible Vault - Keeping secrets secret
      • Variable Precedence
    • If/then/when - Conditionals
      • Jinja2 Expressions, Python built-ins, and Logic
      • register
      • when
      • changed_when and failed_when
      • ignore_errors
    • Delegation, Local Actions, and Pauses
      • Pausing playbook execution with wait_for
      • Running an entire playbook locally
    • Prompts
    • Tags
    • Blocks
    • Summary
  • Chapter 6 - Playbook Organization - Roles and Includes
    • Includes
      • Dynamic includes
      • Handler includes
      • Playbook includes
      • Complete includes example
    • Roles
      • Role scaffolding
      • Building your first role
      • More flexibility with role vars and defaults
      • Other role parts: handlers, files, and templates
        • Handlers
        • Files and Templates
      • Organizing more complex and cross-platform roles CONTENTS
    • Ansible Galaxy
      • Getting roles from Galaxy
        • Using role requirements files to manage dependencies
      • A LAMP server in nine lines of YAML
      • A Solr server in eight lines of YAML
      • Helpful Galaxy commands
      • Contributing to Ansible Galaxy
    • Summary
  • Chapter 7 - Inventories
    • A real-world web application server inventory
      • Non-prod environments, separate inventory files
    • Inventory variables
      • host_vars
      • group_vars
    • Ephemeral infrastructure: Dynamic inventory
      • Dynamic inventory with DigitalOcean
        • DigitalOcean account prerequisites
        • Connecting to your DigitalOcean account
        • Creating a droplet with Ansible
        • DigitalOcean dynamic inventory with digital_ocean.py
      • Dynamic inventory with AWS
      • Inventory on-the-fly: add_host and group_by
      • Multiple inventory sources - mixing static and dynamic inventories
      • Creating custom dynamic inventories
        • Building a Custom Dynamic Inventory in Python
        • Building a Custom Dynamic Inventory in PHP
        • Managing a PaaS with a Custom Dynamic Inventory
    • Summary
  • Chapter 8 - Ansible Cookbooks
    • Highly-Available Infrastructure with Ansible
      • Directory Structure
      • Individual Server Playbooks
      • Main Playbook for Configuring All Servers
      • Getting the required roles CONTENTS
      • Vagrantfile for Local Infrastructure via VirtualBox
      • Provisioner Configuration: DigitalOcean
      • Provisioner Configuration: Amazon Web Services (EC2)
      • Summary
    • ELK Logging with Ansible
      • ELK Playbook
      • Forwarding Logs from Other Servers
      • Summary
    • GlusterFS Distributed File System Configuration with Ansible
      • Configuring Gluster - Basic Overview
      • Configuring Gluster with Ansible
      • Summary
    • Mac Provisioning with Ansible and Homebrew
      • Running Ansible playbooks locally
      • Automating Homebrew package and app management
      • Configuring Mac OS X through dotfiles
      • Summary
    • Docker-based Infrastructure with Ansible
      • A brief introduction to Docker containers
      • Using Ansible to build and manage containers
      • Building a Flask app with Ansible and Docker
        • Data storage container
        • Flask container
        • MySQL container
      • Ship it!
      • Summary
  • Chapter 9 - Deployments with Ansible
    • Deployment strategies
    • Simple single-server deployments
      • Provisioning a Ruby on Rails server
      • Deploying a Rails app to the server
      • Provisioning and Deploying the Rails App
      • Deploying application updates
    • Zero-downtime multi-server deployments
      • Ensuring zero downtime with serial and integration tests CONTENTS
      • Deploying to app servers behind a load balancer
    • Capistrano-style and blue-green deployments
    • Additional Deployment Features
    • Summary
  • Chapter 10 - Server Security and Ansible
    • A brief history of SSH and remote access
      • Telnet
      • rlogin, rsh and rcp
      • SSH
      • The evolution of SSH and the future of remote access
    • Use secure and encrypted communication
    • Disable root login and use sudo
    • Remove unused software, open only required ports
    • Use the principle of least privilege
      • User account configuration
      • File permissions
    • Update the OS and installed software
      • Automating updates
      • Automating updates for RHEL systems
      • Automating updates for Debian-based systems
    • Use a properly-configured firewall
      • Configuring a firewall with ufw on Debian or Ubuntu
      • Configuring a firewall with firewalld on RHEL, Fedora, or CentOS
    • Make sure log files are populated and rotated
    • Monitor logins and block suspect IP addresses
    • Use SELinux (Security-Enhanced Linux) or AppArmor
    • Summary and further reading
  • Chapter 11 - Automating Your Automation - Ansible Tower and CI/CD
    • Ansible Tower
      • Getting and Installing Ansible Tower
      • Using Ansible Tower
      • Other Tower Features of Note
      • Tower Alternatives
    • Jenkins CI CONTENTS
      • Build a local Jenkins server with Ansible
      • Create an Ansible playbook on the Jenkins server
      • Create a Jenkins job to run an Ansible Playbook
    • Unit, Integration, and Functional Testing
      • Debugging and Asserting
        • The debug module
        • The fail and assert modules
      • Checking syntax and performing dry runs
      • Automated testing on GitHub using Travis CI
        • Setting up a role for testing
        • Testing the role’s syntax
        • Role success - first run
        • Role idempotence
        • Role success - final result
        • Some notes about Travis CI
        • Real-world examples
      • Functional testing using serverspec
    • Summary
  • Afterword
  • Appendix A - Using Ansible on Windows workstations
    • Prerequisites
    • Set up an Ubuntu Linux Virtual Machine
    • Log into the Virtual Machine
    • Install Ansible
    • Summary
  • Appendix B - Ansible Best Practices and Conventions
    • Playbook Organization
      • Write comments and use name liberally
      • Include related variables and tasks
      • Use Roles to bundle logical groupings of configuration
      • Use role defaults and vars correctly
    • YAML Conventions and Best Practices
    • YAML for Ansible tasks CONTENTS
    • Three ways to format Ansible tasks
      • Shorthand/one-line (key=value)
      • Structured map/multi-line (key:value)
      • Folded scalars/multi-line (>)
    • Using | to format multiline variables
  • Using ansible-playbook
  • Use Ansible Tower
  • Specify --forks for playbooks running on > 5 servers
  • Use Ansible’s Configuration file
  • Summary

Foreword

Over the last few years, Ansible has rapidly become one of the most popular IT automation tools in the world. We’ve seen the open source community expand from the beginning of the project in early 2012 to over 1200 individual contributors today. Ansible’s modular architecture and broad applicability to a variety of automation and orchestration problems created a perfect storm for hundreds of thousands of users worldwide.

Ansible is a general purpose IT automation platform, and it can be used for a variety of purposes. From configuration management: enforcing declared state across your infrastructure, to procedural application deployment, to broad multi-component and multi-system orchestration of complicated interconnected systems. It is agentless, so it can coexist with legacy tools, and it’s easy to install, configure, and maintain.

Ansible had its beginnings in 2012, when Michael DeHaan, the project’s founder, took inspiration from several tools he had written prior, along with some hands-on experience with the state of configuration management at the time, and launched the project in February of 2012. Some of Ansible’s unique attributes like its module-based architecture and agentless approach quickly attracted attention in the open source world.

In 2013, Said Ziouani, Michael DeHaan, and I launched Ansible, Inc. We wanted to harness the growing adoption of Ansible in the open source world, and create products to fill the gaps in the IT automation space as we saw them. The existing tools were complicated, error-prone, and hard to learn. Ansible gave users across an IT organization a low barrier of entry into automation, and it could be deployed incrementally, solving as few or as many problems as the team needed without a big shift in methodology.

This book is about using Ansible in a DevOps environment. I’m not going to try to define what DevOps is or isn’t, or who’s doing it or not. My personal interpretation of the idea is that DevOps is meant to shorten the distance between the developers writing the code, and the operators running the application. Now, I don’t believe

Preface

Growing up, I had access to a world that not many kids ever get to enter. At the local radio stations where my dad was chief engineer, I was fortunate to get to see networks and IT infrastructure up close: Novell servers and old Mac and Windows workstations in the ’90s; Microsoft and Linux-based servers; and everything in between. Best of all, he brought home decommissioned servers and copies of Linux burned to CD.

I began working with Linux and small-scale infrastructures before I started high school, and my passion for infrastructure grew as I built a Cat5 wired network and a small rack of networking equipment for a local grade school. When I started developing full-time, what was once a hobby became a necessary part of my job, so I invested more time in managing infrastructure efficiently. Over the past ten years, I’ve gone from manually booting and configuring physical and virtual servers; to using relatively complex shell scripts to provision and configure servers; to using configuration management tools to manage many cloud-based servers.

When I began converting my infrastructure to code, some of the best tools for testing, provisioning, and managing my servers were still in their infancy, but they have since matured into fully-featured, robust tools that I use every day. Vagrant is an excellent tool for managing local virtual machines to mimic real-world infrastructure locally (or in the cloud), and Ansible — the subject of this book — is an excellent tool for provisioning servers, managing their configuration, and deploying applications, even on my local workstation!

These tools are still improving rapidly, and I’m excited for what the future holds. The time I invest in learning new infrastructure tools well will be helpful for years to come. (Ansible, Docker, and Vagrant seem a potent combination for both local and production infrastructure, but that’s a little outside of this book’s scope.)

In these pages, I’ll share with you all I’ve learned about Ansible: my favorite tool for server provisioning, configuration management, and application deployment. I hope you enjoy reading this book as much as I did writing it!

— Jeff Geerling, 2015

Preface iv

Who is this book for?

Many of the developers and sysadmins I work with are at least moderately comfort- able administering a Linux server via SSH, and manage between 1-100 servers. Some of these people have a little experience with configuration management tools (usually with Puppet or Chef), and maybe a little experience with deployments and continuous integration using tools like Jenkins, Capistrano, or Fabric. I am writing this book for these friends who, I think, are representative of most people who have heard of and/or are beginning to use Ansible. If you are interested in both development and operations, and have at least a passing familiarity with managing a server via the command line, this book should provide you with an intermediate- to expert-level understanding of Ansible and how you can use it to manage your infrastructure.

Typographic conventions

Ansible uses a simple syntax (YAML) and simple command-line tools (using common POSIX conventions) for all its powerful abilities. Code samples and commands will be highlighted throughout the book either inline (for example: ansible [command]), or in a code block (with or without line numbers) like:

1 --- 2 # This is the beginning of a YAML file.

Some lines of YAML and other code examples require more than 70 characters per line, resulting in the code wrapping to a new line. Wrapping code is indicated by a
at the end of the line of code. For example:

1 # The line of code wraps due to the extremely long URL. 2 wget http://www.example.com/really/really/really/long/path/in/the/ur
3 l/causes/the/line/to/wrap

Preface vi

All known issues with Ansible for DevOps will be aggregated on the book’s online Errata⁴ page.

About the Author

Jeff Geerling is a developer who has worked in programming and reliability engi- neering for companies with anywhere between one to thousands of servers. He also manages many virtual servers for services offered by Midwestern Mac, LLC and has been using Ansible to manage infrastructure since early 2013.

⁴https://www.ansiblefordevops.com/errata

Introduction

In the beginning, there were sysadmins

Since the beginning of networked computing, deploying and managing servers reliably and efficiently has been a challenge. Historically, system administrators were walled off from the developers and users who interact with the systems they administer, and they managed servers by hand, installing software, changing configurations, and administering services on individual servers.

As data centers grew, and hosted applications became more complex, administrators realized they couldn’t scale their manual systems management as fast as the applications they were enabling. That’s why server provisioning and configuration management tools came to flourish.

Server virtualization brought large-scale infrastructure management to the fore, and the number of servers managed by one admin (or by a small team of admins), has grown by an order of magnitude. Instead of deploying, patching, and destroying every server by hand, admins now are expected to bring up new servers, either automatically or with minimal intervention. Large-scale IT deployments now may involve hundreds or thousands of servers; in many of the largest environments, server provisioning, configuration, and decommissioning are fully automated.

Modern infrastructure management

As the systems that run applications become an ever more complex and integral part of the software they run, application developers themselves have begun to integrate their work more fully with operations personnel. In many companies, development and operations work is integrated. Indeed, this integration is a requirement for modern test-driven application design.

As a software developer by trade, and a sysadmin by necessity, I have seen the power in uniting development and operations—more commonly referred to now as DevOps