Friday, April 4, 2025

how to configure ansible

 

What is ansible?

  • Ansible is a tool that helps you to automate tasks like: Installing software and Updating systems.


Why we use it?

  • We use Ansible to Save time and reduce human errors and the Repetetive Task


Features of ansible?

  • Simple to use (written in YAML)
  • Agentless (no need to install anything on client machines)
  • Open source
  • Works with Linux, Windows, cloud (AWS, GCP, etc.)
  • Idempotent (runs same task many times without changing result)


Ansible architecture and it's components

  • Control Node (Your main computer where you install and run Ansible)
  • Managed Nodes (The computers (servers) you want to control)
  • Inventory File (A list of servers with IPs or hostnames)
  • Playbook (A YAML file that contains the tasks list you want to run)
  • Modules (a module is a small piece of code that does a specific job.)
  • Ad-hoc Commands (One-time quick commands without writing a playbook)



✅ Prerequisites

  • A control node with Ansible installed
  • One or more managed nodes
  • Python installed on all machines
  • SSH access to managed nodes


Step 1) Install Ansible

  • sudo apt update
  • sudo apt install ansible -y
  • ansible --version


Step 2) Create an Ansible Project Directory and more

  • mkdir /etc/ansible/
  • vim  /etc/ansible/hosts.ini

[local]

127.0.0.1 ansible_user=administrator ansible_ssh_pass=654321


✅ Ansible ad-hoc commands


1. Ping all servers

  • ansible all -i hosts -m ping


2. Install a package nginx on Ubuntu "  -b = become (use sudo)  "

  • ansible webservers -i hosts -b -m apt -a "name=nginx state=present"


3. Reboot all servers

  • ansible all -i hosts -b -a "reboot"


4. Copy a file to remote servers

  • ansible all -i hosts -b -m copy -a "src=/home/user/file.txt dest=/tmp/file.txt"




#copy_files.yml

---
- name: Copying files to remote
hosts: all

tasks:
- name: Copy files
copy:
src: /root/myfile.txt
dest: /tmp/
owner: paul
group: paul
mode: ugo=rw
backup: true

#files_mod.yml

---
- name: File Module
hosts: all

tasks:
- name: Creating a file
file:
path: /tmp/newfile.txt
state: absent
owner: paul
group: paul
mode: u=rwx,g=rw,o=r

- name: Creating a directory
file:
path: /tmp/myfolder
state: absent

#change_permission.yml

---
- name: change permissions
hosts: all

tasks:
- name: change perm
file:
path: /tmp/myfile.txt
mode: u=r,g=rw

#script_run.yml

---
- name: Run a script
hosts: all

tasks:
- name: Run script
shell: ./test.sh >> test.log
args:
chdir: /tmp/script/
creates: test.log


#download_file.yml

---
- name: Downlaod files
hosts: all

tasks:
- name: Download file
get_url:
url: https://www.python.org/ftp/python/3.12.2/Python-3.12.2.tar.xz
dest: /tmp/script/
owner: paul
group: paul
mode: 0777



ansible-playbook -i hosts.ini playbook.yml --syntax-check

ansible-playbook -i hosts.ini playbook.yml






No comments:

Post a Comment

testing