Ansible Cheat Sheet: 2022 Edition

In this Ansible Cheat Sheet you can find commands which might be needed in daily life that working on ansible. This Ansible Cheat Sheet has fully covered any and all Ansible related queries that you may face working on Ansilbe.

Ansible is an open-source platform, or tool, used for IT automation tasks such as configuration management, application deployment, orchestration, and cloud provisioning. With the abruptly advancing field of IT, automation is considered crucial in modern days. To manage the growing IT environments that are too complex, it is humanly impossible for system administrators and developers to keep up the pace if everything needs to get managed manually.

The primary purpose of automation is to break down complex tasks that are manageable in simpler ways. Automation not only makes developers’ jobs more manageable but also enables them to focus on more value-added tasks for an organization. In simpler words, it buys you time and increases efficiency. Ansible being an automation tool, is climbing the ladder of popularity rapidly and becoming a top choice in the world of automation tools.

How Ansible Works?
Here is how according to Ansible Cheat Sheet:

Ansible connect nodes with each other. It then pushes small programs called modules to those nodes. Moreover, when these modules are done, it removes them. The process follows as under:

  • The main management node controls the whole execution of the playbook.
  • The inventory file provides a list of hosts where the modules need to be run.
  • ‘SSH’ connections are carried out by the management node, and it executes the modules and then installs the software.

Setting up Environment – Ansible Cheat Sheet

It is very important to understand how to set up an Ansible machine before moving forward to work with commands. There are two types of machines that are used when it comes to deployment. These machines are:

Control Machine: Control machine is the type of machine that helps in managing other machines.

Remote Machine: As suggested by the name, the remote machine is the one that gets controlled by the control machine.

A single control machine is capable of handling multiple remote machines, and this is done by default through Ansible. It can be installed through apt, yumpkg, pip, or OpenCSW

To install it through apt, use the following command:

$ sudo apt-get update$ sudo apt-get install software-properties-common$ sudo apt-add-repository ppa:ansible/ansible $ sudo apt-get update$ sudo apt-get install ansible

YAML (Yet Another Markup Language)

YAML is a core component of Ansible. Playbooks are used in Ansible to carry out different tasks. YAML is considered as a human-readable programming language. Its syntax is used to express the Ansible playbooks. Some of the basic concepts of YAML are as under:

Key / Value Pair

Dictionary is represented in key/value pairs. The example is:

john:name: john wickrollNo: 234div: Agender: male

Representing Lists

As a prefix ‘-‘ is used because each element in a list has to be written in a new line:

countries:– America– Germany– China– France– India

Lists Inside a Dictionary

Inside a dictionary, we can have further lists:

john:name: john wickrollNo: 234div: Agender: malelikes:– maths– biology– english

Advantages of Ansible according to Ansible Cheat Sheet

Among the many advantages of using Ansible, few of them are as follows:

Free of Cost: Ansible is free as it is an open-source tool.

Simple to Install and Use: Ansible’s playbooks are easy to use, and no coding skills are necessary to use it.

Flexible: Regardless of your location and time, you can manage the entire application environment. You can also customize it as per your needs.

Powerful: Ansible can model and handle highly complex IT workflows.

Efficient: Without any need to install extra software, there’s more room for application resources on the server, which allows it to work efficiently.

Who Should Obtain an Ansible Certification?

Ansible certification is recommended for both beginners and experts. If you are a beginner and looking forward to a career in IT automation, this certification is a must-have in your resume. Moreover, the Ansible course is ideal for experienced system administrators, software developers, and automation engineering professionals.

In this article, we will go through the Ansible cheat sheet to provide a handy reference to commonly used commands and practices while working with Ansible.

Ansible Cheat Sheet: 2022 Edition - uncookednews

Ansible Terms

For a better understanding of Ansible commands and how they work, let us go through specific terminologies which are as under:

  • Node / Control Machine: A system on which Ansible is installed and configured to connect and run commands on nodes
  • Node: Ansible controlled server
  • Target Machine: A target machine-controlled and configured by Ansible
  • Inventory File: A file that contains information of servers controlled by Ansible
  • Playbook: A file with a chain of tasks to be executed on a remote server which is written in YAML syntax
  • Role: A larger collection of playbooks and several other files to carry out a big task
  • Play: A complete Ansible process. A play contains several playbooks and roles

Ad-hoc Commands

An ad-hoc command is used to do something really quick and urgent, which is not intended for saving in the future. Syntax of an ad-hoc command is as under:

Command hostgroup module/options[arguments]

Further Commands:

Checking the connectivity of hosts#ansible <group> -m ping
Rebooting hosts#ansible <group> -a “/bin/reboot”
Checking the host system’s info#ansible<group> -m steup | less
Transferring files#ansible <group> -m copy -a “src=home/ansible dest=/tmo/home”
Creating a new user#ansible<group> -m user -a “name=ansible password= <encrypted password>”
Deleting a user#ansible<group> -m user -a “name=ansible state- absent”
Checking if a package is installed and updating it#ansible<group> -m yum -a “name=httpd state=latest”
Checking if a package is installed but not to update it#ansible<group> -m yum -a “name=httpd state=present”
Checking if a package is of a specific version#ansible<group> -m yum -a “name=httpd-1.8  state=latest”
Checking if a package is not installed#ansible <group> -m yum -a “name= httpd state= absent
Starting a service#ansible<group> -m service -a “name= httpd state=”started”
Stopping a service#ansible<group> -m service -a “name= httpd state=”stopped”
Restarting a service#ansible<group> -m service -a “name= httpd state=”restarted”
Ansible Cheat Sheet: 2022 Edition - uncookednews - 2021 -

Testing Connectivity

To test the capability of Ansible to connect and run commands and playbooks on nodes, the following command is used:

$ ansible all -m ping

The ping element will test the authenticity of credentials for connecting to the nodes defined in the inventory file. Moreover, in addition to testing, it examines if Ansible can run Python scripts on the remote server or not. A pong reply gives a signal that Ansible is ready to run commands and playbooks on that particular node.

Connecting as a Different User

Ansible, by default, is programmed to connect to the nodes as your current system user, using its matching SSH keypair. To connect as a different user, attach the command with the -u flag with the name of the specific user:

$ ansible all -m ping -u john

The same is in case of ansible-playbook

$ ansible-playbook myplaybook.yml -u john

Use of Custom SSH Key

To connect to the remote servers while using a custom SSH key, it is provided at the time of execution with the –private-key option:

$ ansible all -m ping –private-key=~/.ssh/custom_id

In case of ansible-playbook:

$ ansible-playbook myplaybook.yml –private-key=~/.ssh/custom_id

Password-Based Authentication

If you are looking to use password-based authentication for connecting to the nodes, you will need to add the option –ask-pass to Ansible command. It will make Ansible ask you for the user password on the remote server which you’re attempting to connect:

$ ansible all -m ping –ask-pass

In the case of ansible-playbook:

$ ansible-playbook myplaybook.yml –ask-pass

Using the ‘sudo’ Password

To run sudo commands, if the remote user is required to provide a password, an option –ask-become-pass can be added to your Ansible command. It will ask you to provide the remote user sudo password:

$ ansible all -m ping –ask-become-pass

In the case of ansible-playbook:

$ ansible-playbook myplaybook.yml –ask-become-pass

Custom Inventory File

The default inventory file is usually located at /etc/ansible/hosts. However, when running Ansible commands and playbooks, the -I option can also be used to point to custom inventory files. It is useful for setting up project-specific inventories which can be included in version control systems like Git:

$ ansible all -m ping -i my_custom_inventory

In case of ansible-playbook:

$ ansible-playbook myplaybook.yml -i my_custom_inventory

Dynamic Inventory File

To build dynamic inventory files, inventory scripts are supported by Ansible. It can be beneficial if inventory fluctuates due to the continuous making and breaking of servers.

Several open-source inventory scripts are available on the official Ansible GitHub database. After downloading and setting up the desired script and any required information on your Ansible control machine, you can use the executable file as custom inventory with any Ansible command that backs this particular option.

The following command is used by Ansible’s inventory of script with a ping command to check connectivity to all current active servers:

$ ansible all -m ping -i XYZCompany.py

Running Ad-hoc Commands

To execute a command on a node, -a option is used, followed by the desired command, in quotes. The command will run uname -a on all the available nodes in inventory:

$ ansible all -a “uname -a”

Moreover, you can run Ansible modules with the option -m. The command given below would install the vim package on server1 from your inventory:

$ ansible server1 -m apt -a “name=vim”

Before making any changes to nodes, a dry run can also be conducted to forecast how the servers would behave under your command. It can be done by adding the –check option:

$ ansible server1 -m apt -a “name=vim” –check

Ansible Cheat Sheet : Playbooks

If you want to run and execute a playbook and all the tasks defined within it, use the following ansible-playbook command:

$ ansible-playbook myplaybook.yml

While in order overwrite the hosts’ option set by default in the playbook and restricting its execution to a certain group or host, you must include the option -l in the command:

$ ansible-playbook -l server1 myplaybook.yml

To Get Information about a Play

To list all tasks you need to execute by a play without forcing any changes to the remote servers, –list-tasks option is used:

$ ansible-playbook myplaybook.yml –list-tasks

Likewise, it is also possible to enlist all hosts which are likely to be affected by a play, without having to run any tasks on the remote servers:

$ ansible-playbook myplaybook.yml –list-hosts

Furthermore, tags can also be used to limit the execution of a play. The option –list-tags is used to list all tags available in a play:

$ ansible-playbook myplaybook.yml –list-tags

Playbook Execution

To define a new entry point in your playbook, –start-at-task option can be used. Ansible will then filter out any other task that comes before your specified task. It will execute the remaining of the play from your new entry point:

$ ansible-playbook myplaybook.yml –start-at-task=”Set Up Nginx”

You can use the option –tags to execute tasks associated with certain tags specifically. To illustrate, if you want to execute tasks tagged as Nginx or MySQL only, you must use:

$ ansible-playbook myplaybook.yml –tags=mysql,Nginx

If you want to skip all the tasks related to specific tags, for example, MySQL, –skip-tags options are used. The command given under would execute myplaybook.yml while skipping all tasks tagged as MySQL:

$ ansible-playbook myplaybook.yml –skip-tags=mysql

Ansible Vault – Storage of Sensitive Data

An encryption mechanism is mandatory and vital if you intend to use sensitive data like passwords, API keys, and credentials in your Ansible playbooks. For this purpose, Ansible provides an ansible-vault to encrypt data and files.

Although Ansible allows you to encrypt any data file as well as binary files. However, ansible-vault to encrypt variable files containing sensitive data is mostly used. After encrypting a file with this tool, it prompts you to provide the relevant password to execute, edit, or view its contents:

How to Create a New Encrypted File

A new encrypted Ansible file can be created with:

$ ansible-vault create credentials.yml

The command mentioned above will perform the following actions:

  • It will ask you to enter a new password. Every time you want to access the file contents for viewing, editing, or just running playbooks, you will need to provide the password.
  • After providing the password, it will open the default command-line editor, enabling you to find the file with the wanted contents.
  • Lastly, after editing finishes, the file is saved as encrypted data by ansible-vault.

Encrypting an Existing File

The following syntax can be used to encrypt an existing Ansible file:

$ ansible-vault encrypt credentials.yml

It will make you provide a password whenever you want to access the file credentials.yml

Viewing the Contents of Encrypted File

The contents of a previously encrypted file with ansible-vault can be viewed by using:

$ ansible-vault view credentials.yml

It will make you provide a password which you created while encrypting with ansible-vault:

$ ansible-vault view credentials.yml

Editing an Encrypted File

To edit the contents of a previously encrypted file with Ansible Vault, you can use:

$ ansible-vault edit credentials.yml

Using this command will ask you to provide the password you selected while first encrypting the file credentials.yml with ansible-vault. After approving the password, you will get access to the default command-line editor, which will open the unencrypted contents of the file. It will enable you to make your changes. After making desired changes, you can save and close the file, and the updated contents will automatically be saved as encrypted data.

Decrypting Encrypted Files

If you wish to permanently revert a file that was previously encrypted with ansible-vault to its unencrypted version, you can do so with this syntax:

$ ansible-vault decrypt credentials.yml

This command will prompt you to enter the same password set up when initially encrypting the file credentials.yml with ansible-vault. After password endorsement, the file contents will be saved as unencrypted data.

Multiple Vault Passwords

Ansible allows multiple vault passwords to be used by different vault IDs. This feature is handy if you decide to have separate vault passwords for different settings, for example, testing, development, and production.

To create a new encrypted file using a custom vault ID, –vault-id option is included with a label and the location where ansible-vault can find the password for specific vault. The label can be any identifier, and the location can either be a prompt to enter a password or a valid path leading to a password file.

$ ansible-vault create –vault-id dev@prompt credentials_dev.yml

This command will make a new vault ID named dev, which uses prompt as password source. You will enable you to have separate ansible vaults for each application environment, by combining this method with group variable files:

$ ansible-vault create –vault-id prod@prompt credentials_prod.yml

You would have noticed that dev and prod have been used as vault IDs to exhibit how separate vaults for each environment can be created. However, you can create as many vaults as you may require while using any identifier as a vault ID.

Moving forward, to view, edit, or decrypt these files, the same vault ID and password source along with the ansible-vault command is needed:

$ ansible-vault edit credentials_dev.yml –vault-id dev@prompt

Using Playbook with Data Encrypted Through Ansible Vault

You will be required to provide the vault password to your playbook command whenever you wish to run a playbook with data previously encrypted via ansible-vault. When encrypting the data used in the playbook, if you have previously used default options and the password source, to make Ansible prompt you for the password the option –ask-vault-pass can be used:

$ ansible-playbook myplaybook.yml –ask-vault-pass

Instead of prompting for the password, if password file was being used, then –vault-password-file option must be used instead:

$ ansible-playbook myplaybook.yml –vault-password-file my_vault_password.py

Moreover, the same vault ID and password source being used when first encrypting the data must be provided if you are using data encrypted under a vault ID:

$ ansible-playbook myplaybook.yml –vault-id dev@prompt

While using a password file with your vault ID, the label followed by the full path to the password file must be provided as password source:

$ ansible-playbook myplaybook.yml –vault-id dev@vault_password.py

Last but not least, if you are using multiple vaults in play, a –vault-id parameter must be provided for each of them, in whatever order you want:

$ ansible-playbook myplaybook.yml –vault-id dev@vault_password.py –vault-id test@prompt –vault-id ci@prompt

Debugging according to Ansible Cheat Sheet

If you, by chance, face some errors while executing Ansible commands and playbooks, increased output prolixity is advised to get more detailed information about the specific problem. Adding a -v option to the command can be used to do so:

$ ansible-playbook myplaybook.yml -v

If you desire more detailed insights, using -vvv will ultimately increase the verbosity of the output. If you’re finding it difficult to connect to the remote nodes via Ansible, using -vvvv option can lead you to connection debugging information:

$ ansible-playbook myplaybook.yml -vvvv
Ansible Cheat Sheet: 2022 Edition - uncookednews - 2021

The Future for IT Professionals is Ansible!
Ansible Cheat Sheet

Ansible is for everyone related to the IT industry. This technology is not only related to the IT Infrastructure and Maintenance field, which is usually taken care of by the IT Administrators or the deployment teams. But also it holds great importance for developers alike, and you, as a developer, must understand the task written in the playbooks.

Ansible is a must-have technology under your belt. In recent times of abrupt IT developments, every organization’s goal is to automate all the processes which they possibly can to increase the overall efficiency and productivity of the applications, resources, and workforce. There is a constant need for server configuration and management of big enterprise applications, which are usually deployed in various servers across the globe. This massive and continuous configuration and management require a good amount of time and effort.

If you are adept in automation tools like Ansible and have a good command over it, this will certainly help you in your career growth. We advise looking into Ansible and gaining the experience for a better future. Good luck with the career advancement in Ansible!