https://zwischenzugs.com/2021/08/27/five-ansible-techniques-i-wish-id-known-earlier/ Skip to content [4f37af910d] zwischenzugs Five Ansible Techniques I Wish I'd Known Earlier zwischenzugs Uncategorized August 27, 2021 5 Minutes If you've ever spent ages waiting for an Ansible playbook to get through a bunch of tasks so yours can be tested, then this article is for you. Ansible can be pretty tedious to debug and obscure to develop at times ("What's the array I need to access the IP address on the en2 interface again?"), so I went looking for various ways to speed up the process, and make it easier to figure out what is going on. Eventually I found five tools or techniques that can help, so here they are. These tips go in order from easiest to hardest to implement/use. 1) --step This is the simplest of the techniques to implement and follow. Just add --step to your ansible-playbook command, and for each task you run you will get a prompt that looks like this: PLAY [Your play name] **************************************************************************************** Perform task: TASK: Your task name (N)o/(y)es/(c)ontinue: For each task, you can choose to run the task (yes), not run the task (no, the default), or run the rest of the play (continue). Note that continue will run until the end of the play, not the end of the entire run. Quite handy if you know you want to say yes to everything in the current playbook. The downside is that if there are many tasks to get through, you have to be careful not to keep your finger on the return key and accidentally go to far. It would be a nice little open source project for someone to make this feature more powerful, adding 'back' and 'skip this playbook' features. 2) Inline logging In addition to runtime control, you can use old-fashioned log lines to help determine what's going on. The following snippet of code will 'nicely' dump out json representations of the variables set across all the hosts. This is really handy if you want to know where Ansible has some information you want to reference in your scripts. - name: dump all hosts: all tasks: - name: Print some debug information vars: msg: | Module Variables ("vars"): -------------------------------- {{ vars | to_nice_json }} ================================ Environment Variables ("environment"): -------------------------------- {{ environment | to_nice_json }} ================================ Group Variables ("groups"): -------------------------------- {{ groups | to_nice_json }} ================================ Host Variables ("hostvars"): -------------------------------- {{ hostvars | to_nice_json }} ================================ debug: msg: "{{ msg.split('\n') }}" tags: debug_info As you'll see later, you can also interrogate the Python environment interactively... 3) Run ansible-lint As with most linters, ansible-lint can be a great way to spot problems and anti-patterns in your code. Its output includes lines like this: roles/rolename/tasks/main.yml:8: risky-file-permissions File permissions unset or incorrect You configure it with a .ansible-lint file, where you can suppress classes of error, or just tell you to warn. The list of rules are available here, and more documentation is available here. 4) Run ansible-console This can be a huge timesaver when developing your Ansible code, but unfortunately there isn't much information or guidance out there on how to use it, so I'm going to go into a bit more depth here. The simplest way to run it is just as you would a playbook, but with console instead of playbook: $ ansible-console -i hosts.yml Welcome to the ansible console. Type help or ? to list commands. imiell@all (1)[f:5]$ You are greeted with a prompt and some advice. If you type help, you get a list of all the commands and modules available to you to use in the context in which you have run ansible-console: Documented commands (type help ): ======================================== EOF dpkg_selections include_vars setup add_host exit iptables shell apt expect known_hosts slurp apt_key fail lineinfile stat apt_repository fetch list subversion assemble file meta systemd assert find package sysvinit async_status forks package_facts tempfile async_wrapper gather_facts pause template become get_url ping timeout become_method getent pip unarchive become_user git raw uri blockinfile group reboot user cd group_by remote_user validate_argument_spec check help replace verbosity command hostname rpm_key wait_for copy import_playbook script wait_for_connection cron import_role serial yum debconf import_tasks service yum_repository debug include service_facts diff include_role set_fact dnf include_tasks set_stats You can ask for help on these. If it's a built-in command, you get a brief description, eg: imiell@all (1)[f:5]$ help become_user Given a username, set the user that plays are run by when using become or, if it's a module, you get a very handy overview of the module and its parameters: imiell@all (1)[f:5]$ help shell Execute shell commands on targets Parameters: creates A filename, when it already exists, this step will B(not) be run. executable Change the shell used to execute the command. chdir Change into this directory before running the command. cmd The command to run followed by optional arguments. removes A filename, when it does not exist, this step will B(not) be run. warn Whether to enable task warnings. free_form The shell module takes a free form command to run, as a string. stdin_add_newline Whether to append a newline to stdin data. stdin Set the stdin of the command directly to the specified value. Where the console comes into its own is when you want to experiment with modules quickly. For example: imiell@basquiat (1)[f:5]$ shell touch /tmp/asd creates=/tmp/asd basquiat | CHANGED | rc=0 >> imiell@basquiat (1)[f:5]$ shell touch /tmp/asd creates=/tmp/asd basquiat | SUCCESS | rc=0 >> skipped, since /tmp/asd exists If you have multiple hosts, it will run across all those hosts. This is a great way to broadcast commands across a wide range of hosts. If you want to work on specific hosts, or , then use the cd command, which (misleadingly) changes your host context rather than directory. You can choose a specific host, or a group of hosts. By default, it uses all: imiell@all (4)[f:5]$ cd basquiat imiell@basquiat (1)[f:5]$ command hostname basquiat | CHANGED | rc=0 >> basquiat If a command doesn't match an Ansible command or module, it assumes it's a normal shell command and runs it through one of the Ansible shell modules: imiell@basquiat (1)[f:5]$ echo blah basquiat | CHANGED | rc=0 >> blah The console has autocomplete, which can be really handy when you're playing around: imiell@basquiat (1)[f:5]$ expect chdir= command= creates= echo= removes= responses= timeout= imiell@basquiat (1)[f:5]$ expect 5) The Ansible Debugger Ansible also contains a debugger that you can use to interrogate a running Ansible process. In this example, create a file called playbook.yml, add this play to an existing one, or modify an existing play: - hosts: all debugger: on_failed gather_facts: no tasks: - fail: $ ansible-playbook playbook.yml PLAY [all] *************************** TASK [fail] ************************** Friday 27 August 2021 12:16:24 +0100 (0:00:00.282) 0:00:00.282 ********* fatal: [Ians-Air.home]: FAILED! => {"changed": false, "msg": "Failed as requested from task"} [Ians-Air.home] help EOF c continue h help p pprint q quit r redo u update_task From there, you can execute Python commands directly to examing the context: [Ians-Air.home] TASK: wrong variable (debug)> dir() ['host', 'play_context', 'result', 'task', 'task_vars'] Or use the provided commands to help you debug. For example, p maps to a pretty-print command: [Ians-Air.home] TASK: wrong variable (debug)> p dir(task) ['DEPRECATED_ATTRIBUTES', '__class__', '__delattr__', '__dict__', '__doc__', [...] 'tags', 'throttle', 'untagged', 'until', 'validate', 'vars', 'when'] --------------------------------------------------------------------- If you like this, you might like one of my books: Learn Bash the Hard Way Learn Git the Hard Way Learn Terraform the Hard Way LearnGitBashandTerraformtheHardWayBuy in a bundle here --------------------------------------------------------------------- If you enjoyed this, then please consider buying me a coffee to encourage me to do more. [bmc-button] Share this: * Email * * * Tweet * Share on Tumblr * Pocket * * Like this: Like Loading... Related [4f37af910d] Published by zwischenzugs View all posts by zwischenzugs Published August 27, 2021 Post navigation Previous Post A 'Hello World' GitOps Example Walkthrough 2 thoughts on "Five Ansible Techniques I Wish I'd Known Earlier" 1. Pingback: Five Ansible Techniques I Wish I'd Known Earlier - The web development company 2. Pingback: Five Ansible Techniques I Wish I'd Known Earlier - MadGhosts Leave a Reply Cancel reply Enter your comment here... [ ] Fill in your details below or click an icon to log in: * * * * Gravatar Email (required) (Address never made public) [ ] Name (required) [ ] Website [ ] WordPress.com Logo You are commenting using your WordPress.com account. ( Log Out / Change ) Google photo You are commenting using your Google account. ( Log Out / Change ) Twitter picture You are commenting using your Twitter account. ( Log Out / Change ) Facebook photo You are commenting using your Facebook account. ( Log Out / Change ) Cancel Connecting to %s [ ] Notify me of new comments via email. [ ] Notify me of new posts via email. [Post Comment] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] This site uses Akismet to reduce spam. Learn how your comment data is processed. Follow me on Twitter My Tweets Top Posts & Pages * Five Ansible Techniques I Wish I'd Known Earlier * Bash to Python Converter * How (and Why) I Run My Own DNS Servers * Anatomy of a Linux DNS Lookup - Part I * Ten Things I Wish I'd Known Before Using Jenkins Pipelines * A 'Hello World' GitOps Example Walkthrough * If You Want To Transform IT, Start With Finance * Goodbye Docker: Purging is Such Sweet Sorrow * Convert Any Server to a Docker Container (Updated) * Convert Any Server to a Docker Container Recent Posts * Five Ansible Techniques I Wish I'd Known Earlier * A 'Hello World' GitOps Example Walkthrough * If You Want To Transform IT, Start With Finance * How To Waste Hundreds of Millions on Your IT Transformation * When Should I Interrupt Someone? * An Incompetent Newbie Takes Up 3D Printing * GitOps Decisions * Five Ways to Undo a Commit in Git * The Halving of the Centre: Covid and its Effect on London Property * Why Do We Have Dev Rels Now? * The Runbooks Project * Some Relatively Obscure Bash Tips * Riding the Tiger: Lessons Learned Implementing Istio * The Astonishing Prescience of Nam June Paik * Notes on Books Read in 2019 * The First Non-Bullshit Book About Culture I've Read * Why Everyone Working in DevOps Should Read The Toyota Way * Surgically Busting the Docker Cache * Software Security Field Guide for the Bewildered * The Lazy Person's Guide to the Info Command * A Hot Take on GitHub Actions * Seven God-Like Bash History Shortcuts You Will Actually Use * How Long Will It Take For The Leavers To Leave? * Goodbye Docker: Purging is Such Sweet Sorrow * Seven Surprising Bash Variables * The Missing Readline Primer * Apple's HQ, Ruskin, Gothic Architecture, and Agile * Eight Obscure Bash Options You Might Want to Know About * 'AWS vs K8s' is the new 'Windows vs Linux' * Pranking the Bash Binary * Bash Startup Explained * Git Hooks the Hard Way * Notes on Books Read in 2018 * Six Ways to Level Up Your nmap Game * Five Things I Wish I'd Known About Git * Eleven bash Tips You Might Want to Know * Learn Bash Debugging Techniques the Hard Way * Why Are Enterprises So Slow? * Anatomy of a Linux DNS Lookup - Part V - Two Debug Nightmares * Anatomy of a Linux DNS Lookup - Part IV * Anatomy of a Linux DNS Lookup - Part III * Anatomy of a Linux DNS Lookup - Part II * Anatomy of a Linux DNS Lookup - Part I * A Docker Image in Less Than 1000 Bytes * Autotrace - Debug on Steroids * Beyond 'Punk Rock Git' in Eleven Steps * Sandboxing Docker with Google's gVisor * Unprivileged Docker Builds - A Proof of Concept * Learn Git Rebase Interactively * Terminal Perf Graphs in one Command * git log - the Good Parts * Five Key Git Concepts Explained the Hard Way * Create Your Own Git Diagrams * Five Things I Did to Change a Team's Culture * Centralise Your Bash History * How (and Why) I Run My Own DNS Servers * Ten More Things I Wish I'd Known About bash * Download a Free Sample of Learn Bash the Hard Way * Ten Things I Wish I'd Known About bash * Project Management as Code with Graphviz * How to Manually Clear Locks in Jenkins * How I Manage My Time * Ten Things I Wish I'd Known About Chef * Vagrant and Ohai / Chef IP Address Hack * 'Towards a National Computer Grid' - Electronic Computers, 1965 * A Complete Chef Infrastructure on Your Laptop * Ten Things I Wish I'd Known Before Using Vagrant * A Checklist for Docker in the Enterprise (Updated) * OpenShift 3.6 DNS In Pictures * Puppeteer - Headless Chrome in a Container * My 20-Year Experience of Software Development Methodologies * A Non-Cloud Serverless Application Pattern Using Git and Docker * Run Your Own AWS APIs on OpenShift * Dockerized Headless Chrome Example * Convert a Server to a Docker Container (Update II) * Automating Dockerized Jenkins Upgrades * Ten Things I Wish I'd Known Before Using Jenkins Pipelines * Five Books I Advise Every DevOps Engineer to Read * Things I Learned Managing Site Reliability for Some of the World's Busiest Gambling Sites * Clustered VM Testing How-To * Easy Shell Automation * 1-Minute Multi-Node VM Setup * Migrating an OpenShift etcd Cluster * A Complete OpenShift Cluster on Vagrant, Step by Step * Learn Kubernetes the Hard Way (the Easy and Cheap Way) * Docker in the Enterprise * Terraform and Dynamic Environments * Bash to Python Converter * Hello world Unikernel Walkthrough * A checklist for Docker in the Enterprise * A Quick Tour of Docker 1.12 * Power 'git log' graphing * ssh -R (reverse tunnel) man page hell * Writing a Technical Book * Interactive Git Tutorials - Rebase and Bisect * Hitler Uses Docker, Annotated * Linux Scales * Play With Kubernetes Quickly Using Docker (Updated) * Convert Any Server to a Docker Container (Updated) * CI as Code Part III: Dynamic Jenkins-Swarm Example * Docker 1.10 Highlights - Updated * CI as Code Part II: Stateless Jenkins With Dynamic Docker Slaves * CI as Code Part I: Stateless Jenkins Deployments Using Docker * Docker Ecosystem Rosetta Stones * Understanding Docker - A Tour of Logical Volume Management * Automating Docker Security Validation * The IT Crowd Was Right - What I learned by reading a lot of RFCs * Understanding Docker - Network Namespaces * DockerConEU 2015 Talk - You Know More Than You Think * Docker Migration In-Flight CRIU * A High Availability Phoenix and A/B Deployment Framework using Docker * Quick Intro to Kubernetes * Take OpenShift for a spin in four commands * RedHat's Docker Build Method - S2I * RedHat's Docker Build Method - S2I * Bash Shortcuts Gem * A CoreOS Cluster in Two Minutes With Four Commands * The Most Pointless Docker Command Ever * My Favourite Docker Tip * Convert Any Server to a Docker Container * A Field Guide to Docker Security Measures * Docker SELinux Experimentation with Reduced Pain * Storage Drivers and Docker * Play With Kubernetes Quickly Using Docker * Play with an OpenShift PaaS using Docker * Scale Your Jenkins Compute With Your Dev Team: Use Docker and Jenkins Swarm * Docker in Practice - A Guide for Engineers * Fight Docker Package Drift! * Win at 2048 with Docker and ShutIt (Redux) * Set Up a Deis (Docker-Friendly) Paas on Digital Ocean for $0.18 Per Hour in Six Easy Steps Using ShutIt * Create your own CoreOS cluster in 6 easy steps for $0.03 * Make Your Own Bespoke Docker Image * Taming Slaves with Docker and ShutIt * Docker - One Year On * Using ShutIt to Build Your Own Taiga Server * Using ShutIt and Docker to play with AWS (Part Two) * Talk on Docker and ShutIt * Using ShutIt and Docker to play with AWS (Part One) * Phoenix deployment pain (and win) * Phoenix Deployment with Docker and ShutIt * Docker, ShutIt and the Perfect 2048 Game (Videos) * Docker, ShutIt and the Perfect 2048 Game (4 - Halfway There) * Docker, ShutIt and the Perfect 2048 Game (3 - Brute Force Escapes) * Docker, ShutIt and the Perfect 2048 Game (2) * Docker, ShutIt, and The Perfect 2048 Game * My Favourite Secret Weapon - strace * Shakespeare's Vocabulary Considered Unexceptional Follow zwischenzugs on WordPress.com Website Built with WordPress.com. Loading Comments... Write a Comment... [ ] Email (Required) [ ] Name (Required) [ ] Website [ ] [Post Comment] Send to Email Address [ ] Your Name [ ] Your Email Address [ ] [ ] loading [Send Email] Cancel Post was not sent - check your email addresses! Email check failed, please try again Sorry, your blog cannot share posts by email. %d bloggers like this: [b]