DEV Community

Cover image for How to install ansible and run your first ansible Ad-Hoc Command.
Kartik
Kartik

Posted on

How to install ansible and run your first ansible Ad-Hoc Command.

Install Ansible and Run Your First Playbook

Prerequisites

  1. Create two EC2 instances:
    • Main instance: Install Ansible.
    • Target instance: The system to configure.

Step 1: Install Ansible on the Main Instance

Commands:

sudo apt update
sudo apt install ansible
Enter fullscreen mode Exit fullscreen mode

Verify Installation:

ansible --version
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up Passwordless Authentication

On the Main Instance:

  1. Generate an SSH Key Pair:
   ssh-keygen
Enter fullscreen mode Exit fullscreen mode

The public key is usually located at ~/.ssh/id_rsa.pub.

  1. Copy the Public Key: Open the file with a text editor (e.g., vim) and copy its contents.

On the Target Instance:

  1. Log in:
   ssh <username>@<target_server_ip>
Enter fullscreen mode Exit fullscreen mode
  1. Paste the Public Key into ~/.ssh/authorized_keys:
   vim ~/.ssh/authorized_keys
Enter fullscreen mode Exit fullscreen mode

Save changes with :wq.

  1. Test SSH: From the main instance:
   ssh <target_server_ip>
Enter fullscreen mode Exit fullscreen mode

Passwordless authentication should now work.


Step 3: Create an Inventory File

  1. Create a file named inventory:
   [webservers]
   192.168.1.10
   192.168.1.11

   [databases]
   192.168.1.20
Enter fullscreen mode Exit fullscreen mode

Step 4: Run Ad-Hoc Commands

  1. Run a Command Across All Servers:
   ansible -i inventory all -m shell -a "command_to_execute"
Enter fullscreen mode Exit fullscreen mode
  1. Example:
   ansible -i inventory webservers -m shell -a "ls -la"
Enter fullscreen mode Exit fullscreen mode

Step 5: Write and Run Playbooks

  1. Create a Playbook (e.g., playbook.yml):
   ---
   - name: Update and upgrade systems
     hosts: all
     become: yes
     tasks:
       - name: Update package lists
         apt:
           update_cache: yes
       - name: Upgrade packages
         apt:
           upgrade: yes
Enter fullscreen mode Exit fullscreen mode
  1. Run the Playbook:
   ansible-playbook playbook.yml -i inventory
Enter fullscreen mode Exit fullscreen mode

By following these steps, you’ll have a basic Ansible setup to manage your infrastructure effortlessly.

Top comments (0)