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:
Generate SSH Key Pair:
Bash
ssh-keygen
Locate the Public Key: The public key is usually located at
~/.ssh/id_
rsa.pub
.Copy the Public Key:
- Manual copying: Open the file in a text editor (e.g.,
nano
,vim
) and copy the key manually.
- Manual copying: Open the file in a text editor (e.g.,
On the Target Instance:
Log in to the Target Instance:
Bash
ssh <username>@<target_server_ip>
Generate an SSH Key Pair on the Target Instance:
Bash
ssh-keygen
Locate the Authorized_keys file: The file will be in
~/.ssh/authorized_keys
.Open the
authorized_keys
file on the Target Instance:Bash
vim ~/.ssh/authorized_keys
Paste the Public Key from the Main Instance: Paste the public key that you copied from the main instance into the
authorized_keys
file.Save and Exit: Press
Esc
to exit insert mode, then type:wq
and pressEnter
to save and quit.
In main instance:
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