DEV Community

Cover image for ๐Ÿ”ง Ansible Commands: From Beginner to Advanced for DevOps Engineers

๐Ÿ”ง Ansible Commands: From Beginner to Advanced for DevOps Engineers

Introduction

Ansible is a powerful automation tool that simplifies the management and configuration of IT infrastructure. It's agentless, meaning it connects to your nodes via SSH or WinRM, making it easy to deploy and manage. This guide provides a comprehensive overview of Ansible commands, from beginner to advanced, to help DevOps engineers efficiently manage their infrastructure.

๐ŸŽฏ Key Concepts

Before we dive into the commands, let's review some fundamental Ansible concepts:

  • Inventory: A list of hosts that Ansible manages.
  • Playbook: A YAML file containing a series of tasks to be executed on the hosts.
  • Module: A command or set of commands executed on the hosts.
  • Role: A way to organize playbooks and other files into reusable components.

๐Ÿ Beginner Commands

1. Setup and Configuration

Check Ansible Version

ansible --version
Enter fullscreen mode Exit fullscreen mode

Displays the installed version of Ansible.

Generate SSH Key

ssh-keygen
Enter fullscreen mode Exit fullscreen mode

Generates an SSH key pair for secure access to remote hosts.

2. Inventory Management

List Hosts in Inventory

ansible all --list-hosts -i inventory
Enter fullscreen mode Exit fullscreen mode

Lists all hosts in the specified inventory file.

Ping Hosts

ansible all -m ping -i inventory
Enter fullscreen mode Exit fullscreen mode

Pings all hosts in the specified inventory to check connectivity.

3. Ad-hoc Commands

Run Command on Remote Hosts

ansible all -m command -a "uname -a" -i inventory
Enter fullscreen mode Exit fullscreen mode

Runs a command on all hosts in the inventory.

Copy File to Remote Hosts

ansible all -m copy -a "src=/local/path dest=/remote/path" -i inventory
Enter fullscreen mode Exit fullscreen mode

Copies a file from the local machine to all hosts.

4. Playbook Execution

Run Playbook

ansible-playbook playbook.yml -i inventory
Enter fullscreen mode Exit fullscreen mode

Executes a playbook on the hosts defined in the inventory.

5. Inventory File

Basic Inventory File

[webservers]
web1 ansible_host=192.168.1.1
web2 ansible_host=192.168.1.2

[dbservers]
db1 ansible_host=192.168.1.3
db2 ansible_host=192.168.1.4
Enter fullscreen mode Exit fullscreen mode

Defines groups of hosts and their IP addresses.

6. Ansible Configuration

Ansible Configuration File

[defaults]
inventory = ./inventory
remote_user = ansible
host_key_checking = False
Enter fullscreen mode Exit fullscreen mode

Configures default settings for Ansible commands.

๐Ÿš€ Intermediate Commands

1. Modules

Install Package

ansible all -m apt -a "name=nginx state=present" -i inventory
Enter fullscreen mode Exit fullscreen mode

Installs the nginx package on all hosts using the apt module.

Start Service

ansible all -m service -a "name=nginx state=started" -i inventory
Enter fullscreen mode Exit fullscreen mode

Starts the nginx service on all hosts using the service module.

2. Facts and Variables

Gather Facts

ansible all -m setup -i inventory
Enter fullscreen mode Exit fullscreen mode

Gathers system information from all hosts.

Use Variables

---
- name: Example playbook
  hosts: all
  vars:
    http_port: 80
  tasks:
    - name: Ensure nginx is installed
      apt:
        name: nginx
        state: present
    - name: Start nginx
      service:
        name: nginx
        state: started
Enter fullscreen mode Exit fullscreen mode

Defines and uses variables in a playbook.

3. Roles

Create Role

ansible-galaxy init myrole
Enter fullscreen mode Exit fullscreen mode

Creates a new role directory structure.

Use Role in Playbook

---
- name: Example playbook
  hosts: all
  roles:
    - myrole
Enter fullscreen mode Exit fullscreen mode

Includes a role in a playbook.

4. Handlers

Define Handler

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Ensure nginx is installed
      apt:
        name: nginx
        state: present
      notify: Restart nginx
  handlers:
    - name: Restart nginx
      service:
        name: nginx
        state: restarted
Enter fullscreen mode Exit fullscreen mode

Defines and uses a handler to restart a service.

5. Templates

Use Template

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Deploy configuration file
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Restart nginx
  handlers:
    - name: Restart nginx
      service:
        name: nginx
        state: restarted
Enter fullscreen mode Exit fullscreen mode

Deploys a configuration file using a Jinja2 template.

6. Vault

Create Encrypted File

ansible-vault create secrets.yml
Enter fullscreen mode Exit fullscreen mode

Creates an encrypted file to store sensitive information.

Edit Encrypted File

ansible-vault edit secrets.yml
Enter fullscreen mode Exit fullscreen mode

Edits an encrypted file.

Use Vault in Playbook

---
- name: Example playbook
  hosts: all
  vars_files:
    - secrets.yml
  tasks:
    - name: Use secret variable
      debug:
        msg: "The secret is {{ secret_variable }}"
Enter fullscreen mode Exit fullscreen mode

Uses an encrypted file in a playbook.

7. Tags

Use Tags in Playbook

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Install nginx
      apt:
        name: nginx
        state: present
      tags: install
    - name: Start nginx
      service:
        name: nginx
        state: started
      tags: start
Enter fullscreen mode Exit fullscreen mode

Defines tags for tasks in a playbook.

Run Playbook with Tags

ansible-playbook playbook.yml -i inventory --tags install
Enter fullscreen mode Exit fullscreen mode

Executes only the tasks with the specified tags.

๐Ÿง  Advanced Commands

1. Dynamic Inventory

Use Dynamic Inventory

ansible-playbook playbook.yml -i dynamic_inventory.py
Enter fullscreen mode Exit fullscreen mode

Uses a dynamic inventory script to get hosts.

2. Custom Modules

Create Custom Module

#!/usr/bin/python

def main():
    module = AnsibleModule(argument_spec=dict(
        name=dict(required=True, type='str')
    ))
    name = module.params['name']
    module.exit_json(changed=False, msg="Hello, %s" % name)

from ansible.module_utils.basic import AnsibleModule
if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Defines a custom Ansible module in Python.

3. Asynchronous Actions

Run Task Asynchronously

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Run long task
      command: /bin/sleep 30
      async: 45
      poll: 0
    - name: Check task result
      async_status:
        jid: "{{ job_id }}"
      register: job_result
      until: job_result.finished
      retries: 5
      delay: 5
Enter fullscreen mode Exit fullscreen mode

Runs a task asynchronously and checks its status.

4. Delegation

Delegate Task to Another Host

---
- name: Example playbook
  hosts: web
  tasks:
    - name: Delegate task to db server
      command: /usr/bin/uptime
      delegate_to: db
Enter fullscreen mode Exit fullscreen mode

Delegates a task to a different host.

5. Looping

Loop Through Items

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Create users
      user:
        name: "{{ item }}"
        state: present
      loop:
        - user1
        - user2
        - user3
Enter fullscreen mode Exit fullscreen mode

Loops through a list of items to create users.

6. Error Handling

Ignore Errors

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Run command and ignore errors
      command: /bin/false
      ignore_errors: yes
Enter fullscreen mode Exit fullscreen mode

Ignores errors for a task.

Retry on Failure

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Retry task on failure
      command: /bin/false
      register: result
      until: result.rc == 0
      retries: 5
      delay: 10
Enter fullscreen mode Exit fullscreen mode

Retries a task until it succeeds.

7. Ansible Galaxy

Install Role from Ansible Galaxy

ansible-galaxy install geerlingguy.nginx
Enter fullscreen mode Exit fullscreen mode

Installs a role from Ansible Galaxy.

Use Installed Role

---
- name: Example playbook
  hosts: all
  roles:
    - geerlingguy.nginx
Enter fullscreen mode Exit fullscreen mode

Uses an installed role in a playbook.

8. Advanced Playbook Structure

Complex Playbook Example

---
- name: Complex playbook
  hosts

: all
  vars_files:
    - vars/main.yml
  tasks:
    - include_tasks: tasks/install.yml
    - include_tasks: tasks/configure.yml
    - include_tasks: tasks/deploy.yml
  handlers:
    - include_tasks: handlers/restart.yml
  roles:
    - role: myrole
      vars:
        role_variable: value
Enter fullscreen mode Exit fullscreen mode

Defines a complex playbook structure with included tasks and handlers.

๐Ÿ“Š Best Practices

Version Control

  • Store your playbooks, roles, and configurations in a version control system like Git to track changes and collaborate effectively.

Modularize Your Code

  • Break down your playbooks into roles and reusable tasks to promote code reuse and manage complexity.

Secure Secrets

  • Use Ansible Vault to encrypt sensitive information and keep it secure.

Test Playbooks

  • Use tools like Molecule to test your playbooks and ensure they work as expected.

Documentation

  • Document your playbooks and roles to make it easier for others to understand and use your code.

Use Idempotent Modules

  • Ensure that the modules you use are idempotent, meaning they can be run multiple times without causing unintended changes.

๐Ÿš€ Conclusion

Mastering Ansible commands from beginner to advanced levels is essential for DevOps engineers to effectively manage and automate infrastructure. This comprehensive guide serves as a valuable reference for navigating your Ansible environment. By following best practices and leveraging these commands, you can ensure a robust and efficient infrastructure setup.

Happy Automating! ๐ŸŽ‰


Thank you for reading my blog โ€ฆ:)

ยฉ Copyrights: ProDevOpsGuy

Join Our Telegram Community || Follow me for more DevOps Content

Top comments (0)