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

·

2 min read

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

Prerequisites: Create two EC2 instances one as main and second as target instance.

1. Install Ansible on main instance:

Bash

  •   sudo apt update
      sudo apt install ansible
    
  • Verify Installation:

Bash

ansible --version

2. Set Up Passwordless Authentication

On the Main Instance:

  1. Generate SSH Key Pair:

    Bash

     ssh-keygen
    
  2. Locate the Public Key: The public key is usually located at ~/.ssh/id_rsa.pub.

  3. Copy the Public Key:

    • Manual copying: Open the file in a text editor (e.g., nano, vim) and copy the key manually.

On the Target Instance:

  1. Log in to the Target Instance:

    Bash

     ssh <username>@<target_server_ip>
    
  2. Generate an SSH Key Pair on the Target Instance:

    Bash

     ssh-keygen
    
  3. Locate the Authorized_keys file: The file will be in ~/.ssh/authorized_keys.

  4. Open the authorized_keys file on the Target Instance:

    Bash

     vim ~/.ssh/authorized_keys
    
  5. Paste the Public Key from the Main Instance: Paste the public key that you copied from the main instance into the authorized_keys file.

  6. Save and Exit: Press Esc to exit insert mode, then type :wq and press Enter to save and quit.

In main instance:

  1.  ssh <target instance ip>
    

Now, when you SSH from the Main Instance to the Target Instance, you should be able to do so without a password.

3. Create an Inventory File

Create a file named inventory and add your target servers:

[webservers]
192.168.1.10
192.168.1.11

[databases]
192.168.1.20

4. Run Ad-Hoc Commands

Execute commands directly on your target servers:

Bash

ansible -i inventory all -m shell -a "command to execute"

Example:

Bash

ansible -i inventory webservers -m shell -a "ls -la"

5. Write Ansible Playbooks

Create a YAML file (e.g., playbook.yml):

YAML

---
- name: Update and upgrade systems
  hosts: all
  become: yes
  tasks:
    - name: Update package lists
      apt:
        update_cache: yes
    - name: Upgrade packages
      apt:
        upgrade: yes

Run the playbook:

Bash

ansible-playbook playbook.yml -i inventory