Install Ansible and Run Your First Playbook
Prerequisites
- 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
Verify Installation:
ansible --version
Step 2: Set Up Passwordless Authentication
On the Main Instance:
- Generate an SSH Key Pair:
ssh-keygen
The public key is usually located at ~/.ssh/id_rsa.pub
.
- Copy the Public Key: Open the file with a text editor (e.g.,
vim
) and copy its contents.
On the Target Instance:
- Log in:
ssh <username>@<target_server_ip>
- Paste the Public Key into
~/.ssh/authorized_keys
:
vim ~/.ssh/authorized_keys
Save changes with :wq
.
- Test SSH: From the main instance:
ssh <target_server_ip>
Passwordless authentication should now work.
Step 3: Create an Inventory File
- Create a file named
inventory
:
[webservers] 192.168.1.10 192.168.1.11 [databases] 192.168.1.20
Step 4: Run Ad-Hoc Commands
- Run a Command Across All Servers:
ansible -i inventory all -m shell -a "command_to_execute"
- Example:
ansible -i inventory webservers -m shell -a "ls -la"
Step 5: Write and Run Playbooks
- 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
- Run the Playbook:
ansible-playbook playbook.yml -i inventory
By following these steps, you’ll have a basic Ansible setup to manage your infrastructure effortlessly.
Top comments (0)