Search This Blog

Friday, 22 August 2025

Ansible_Notes

 

 ansible -i inventory.ini -m ping all   # inventory.ini it will ping to the hosts which are in inventory

# ansible -i inventory.ini -m ping all  --private-key XXXX.pem -u ubuntu # incase above command didn't work

 

[web]
ubuntu@52.10.253.174
[db]
ubuntu@44.229.189.58
 
#ansible -i inventory.ini -m ping web 

#ansible -i inventory.ini -m ping db
 

 

 playbook.yaml # To create a directory in defined path 

- hosts: web
become: true
tasks:
- name: Create a directory on remote machine
file:
path: ./basic-user-dir
state: directory
 

 Dryrun: 

$ ansible-playbook -i inventory.ini playbook.yaml --check --diff

 Run: 

$ ansible-playbook -i inventory.ini playbook.yaml  # --diff to get different

 

Example2 - 

 playbook1.yaml # To create a directory in defined path and confirm the dir creation status

 

ansible-playbook -i inventory.ini Day-1/playbook1.yaml

- hosts: web
become: true
tasks:
- name: Create a directory on remote machine
file:
path: ./boa-user-dir-3
state: directory
register: dir_status
- name: print message if dir is created
debug:
msg: "Directory boa-user-dir is created"
when: dir_status.changed


Output- 
PLAY [web] *****************************************************************************************

TASK [Gathering Facts] *****************************************************************************
[WARNING]: Platform linux on host ubuntu@52.10.253.174 is using the discovered Python interpreter
at /usr/bin/python3.12, but future installation of another Python interpreter could change the
meaning of that path. See https://docs.ansible.com/ansible-
core/2.18/reference_appendices/interpreter_discovery.html for more information.
ok: [ubuntu@52.10.253.174]

TASK [Create a directory on remote machine] ********************************************************
changed: [ubuntu@52.10.253.174]

TASK [print message if dir is created] *************************************************************
ok: [ubuntu@52.10.253.174] => {
    "msg": "Directory boa-user-dir is created"
}

PLAY RECAP *****************************************************************************************
ubuntu@52.10.253.174       : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0    

 Example2 - Completed 

 

Example3 - Install apache2

pyalbook.yamal2

- hosts: web
become: true
tasks:
- name: install apache on web remote machine
apt: name=apache2 update_cache=yes state=latest

- name: check the status of installation
command: systemctl status apache2
register: apache_status

- name: print the status
debug:
msg: "{{apache_status.stdout}}" 
 

 Dry Run: 

 ansible-playbook -i inventory.ini Day-2/playbook2.yaml --check --diff

PLAY [web] *****************************************************************************************

TASK [Gathering Facts] *****************************************************************************
[WARNING]: Platform linux on host ubuntu@52.10.253.174 is using the discovered Python interpreter
at /usr/bin/python3.12, but future installation of another Python interpreter could change the
meaning of that path. See https://docs.ansible.com/ansible-
core/2.18/reference_appendices/interpreter_discovery.html for more information.
ok: [ubuntu@52.10.253.174]

TASK [install apache on web remote machine] ********************************************************
The following additional packages will be installed:
  apache2-bin apache2-data apache2-utils libapr1t64 libaprutil1-dbd-sqlite3
  libaprutil1-ldap libaprutil1t64 liblua5.4-0 ssl-cert
Suggested packages:
  apache2-doc apache2-suexec-pristine | apache2-suexec-custom www-browser
The following NEW packages will be installed:
  apache2 apache2-bin apache2-data apache2-utils libapr1t64
  libaprutil1-dbd-sqlite3 libaprutil1-ldap libaprutil1t64 liblua5.4-0 ssl-cert
0 upgraded, 10 newly installed, 0 to remove and 0 not upgraded.
changed: [ubuntu@52.10.253.174]

TASK [check the status of installation] ************************************************************
skipping: [ubuntu@52.10.253.174]

TASK [print the status] ****************************************************************************
ok: [ubuntu@52.10.253.174] => {
    "msg": ""
}


RUN: 

$ ansible-playbook -i inventory.ini Day-2/playbook2.yaml  --diff

Output - 

 PLAY [web] *****************************************************************************************

TASK [Gathering Facts] *****************************************************************************
[WARNING]: Platform linux on host ubuntu@52.10.253.174 is using the discovered Python interpreter
at /usr/bin/python3.12, but future installation of another Python interpreter could change the
meaning of that path. See https://docs.ansible.com/ansible-
core/2.18/reference_appendices/interpreter_discovery.html for more information.
ok: [ubuntu@52.10.253.174]

TASK [install apache on web remote machine] ********************************************************
The following additional packages will be installed:
  apache2-bin apache2-data apache2-utils libapr1t64 libaprutil1-dbd-sqlite3
  libaprutil1-ldap libaprutil1t64 liblua5.4-0 ssl-cert
Suggested packages:
  apache2-doc apache2-suexec-pristine | apache2-suexec-custom www-browser
The following NEW packages will be installed:
  apache2 apache2-bin apache2-data apache2-utils libapr1t64
  libaprutil1-dbd-sqlite3 libaprutil1-ldap libaprutil1t64 liblua5.4-0 ssl-cert
0 upgraded, 10 newly installed, 0 to remove and 109 not upgraded.
changed: [ubuntu@52.10.253.174]

TASK [check the status of installation] ************************************************************
changed: [ubuntu@52.10.253.174]

 TASK [print the status] ****************************************************************************
ok: [ubuntu@52.10.253.174] => {
    "msg": "● apache2.service - The Apache HTTP Server\n     Loaded: loaded (/usr/lib/systemd/system/apache2.service; enabled; preset: enabled)\n     Active: active (running) since Thu 2025-08-21 05:40:53 UTC; 16s ago\n       Docs: https://httpd.apache.org/docs/2.4/\n   Main PID: 3564 (apache2)\n      Tasks: 55 (limit: 1072)\n     Memory: 5.3M (peak: 5.6M)\n        CPU: 40ms\n     CGroup: /system.slice/apache2.service\n             ├─3564 /usr/sbin/apache2 -k start\n             ├─3566 /usr/sbin/apache2 -k start\n             └─3567 /usr/sbin/apache2 -k start\n\nAug 21 05:40:53 ip-10-0-1-10 systemd[1]: Starting apache2.service - The Apache HTTP Server...\nAug 21 05:40:53 ip-10-0-1-10 systemd[1]: Started apache2.service - The Apache HTTP Server."
}

PLAY RECAP *****************************************************************************************
ubuntu@52.10.253.174       : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

 Validation in console - 


ubuntu@ip-10-0-1-10:~$ systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/usr/lib/systemd/system/apache2.service; enabled; preset: enabled)
     Active: active (running) since Thu 2025-08-21 05:40:53 UTC; 1min 52s ago
       Docs: https://httpd.apache.org/docs/2.4/
   Main PID: 3564 (apache2)
      Tasks: 55 (limit: 1072)
     Memory: 5.3M (peak: 5.6M)
        CPU: 45ms
     CGroup: /system.slice/apache2.service
             ├─3564 /usr/sbin/apache2 -k start
             ├─3566 /usr/sbin/apache2 -k start
             └─3567 /usr/sbin/apache2 -k start

Aug 21 05:40:53 ip-10-0-1-10 systemd[1]: Starting apache2.service - The Apache HTTP Server...
Aug 21 05:40:53 ip-10-0-1-10 systemd[1]: Started apache2.service - The Apache HTTP Server.

Example 3 completed. 

 

Example 4 - executing mail-playbook which is tacking from another file 

 

main-playbook.yaml 

- hosts: web
become: true

pre_tasks:
- name: load the background check
import_tasks: pretask.yaml

tasks:
- name: install software
import_tasks: maintask.yaml 
 

 pretask.yaml

- name: check the background of remote machine
apt:
update_cache: true
cache_valid_time: 3600

- name: Gather OS Information
setup:
gather_subset:
- "os_family"

- name: print OS Information
debug:
msg: "the underlying OS is {{ansible_os_family}}"
 

 

maintask.yaml

  

- name: install apache to the web remote machine
apt:
name:
- apache2
state: latest

- name: chacke the status of installation
command: systemctl status apache2
register: apache_status
- name: print the status
debug:
msg: "{{apache_status.stdout}}"


 

Run: 

 $ ansible-playbook -i inventory.ini Day-2/main-playbook.yaml --diff

 Output - 

 PLAY [web] *****************************************************************************************

TASK [Gathering Facts] *****************************************************************************
[WARNING]: Platform linux on host ubuntu@52.10.253.174 is using the discovered Python interpreter
at /usr/bin/python3.12, but future installation of another Python interpreter could change the
meaning of that path. See https://docs.ansible.com/ansible-
core/2.18/reference_appendices/interpreter_discovery.html for more information.
ok: [ubuntu@52.10.253.174]

TASK [check the background of remote machine] ******************************************************
changed: [ubuntu@52.10.253.174]

TASK [Gather OS Information] ***********************************************************************
ok: [ubuntu@52.10.253.174]

TASK [print OS Information] ************************************************************************
ok: [ubuntu@52.10.253.174] => {
    "msg": "the underlying OS is  Debian"
}

TASK [install apache to the web remote machine] ****************************************************
ok: [ubuntu@52.10.253.174]

TASK [chacke the status of installation] ***********************************************************
changed: [ubuntu@52.10.253.174]

TASK [print the status] ****************************************************************************
ok: [ubuntu@52.10.253.174] => {
    "msg": "● apache2.service - The Apache HTTP Server\n     Loaded: loaded (/usr/lib/systemd/system/apache2.service; enabled; preset: enabled)\n     Active: active (running) since Thu 2025-08-21 06:13:59 UTC; 52min ago\n       Docs: https://httpd.apache.org/docs/2.4/\n   Main PID: 11157 (apache2)\n      Tasks: 55 (limit: 1072)\n     Memory: 5.5M (peak: 5.8M)\n        CPU: 174ms\n     CGroup: /system.slice/apache2.service\n             ├─11157 /usr/sbin/apache2 -k start\n             ├─11159 /usr/sbin/apache2 -k start\n             └─11160 /usr/sbin/apache2 -k start\n\nAug 21 06:13:59 ip-10-0-1-10 systemd[1]: Starting apache2.service - The Apache HTTP Server...\nAug 21 06:13:59 ip-10-0-1-10 systemd[1]: Started apache2.service - The Apache HTTP Server."
}

PLAY RECAP *****************************************************************************************
ubuntu@52.10.253.174       : ok=7    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Example 4 - End 

 

Example 5: Deploying FASTAPI app with ansible 

 

- hosts: web
become: true
pre_tasks:
- name: update cache
apt:
update_cache: true
tasks:
- name: install required software
apt:
name:
- python3
- python3-pip
- python3-venv
state: latest

- name: create FASTAPI dir on remote machine
file:
path: /opt/fastapi_app
state: directory

- name: copy FASTAPI to the destination
copy:
src: fastapi_app/
dest: path:/opt/fastapi_app

- name: create virtual env
command: python3 -m venv /opt/fastapi_app/venv

- name: install fastapi on virtual env
command: /opt/fastapi_app/venv/bin/pip install fastapi uvicorn

- name: run my application
shell:
nohup /opt/fastapi_app/venv/bin/uvicorn main:app --host 0.0.0.0 --port 8000 &
args:
chdir: /opt/fastapi_app


  

RUN: 

~/Documents/python-ansible/ansible-training/Day-2/fastapi_deploy/fastapi_app$ ansible-playbook -i ../../../inventory.ini ../playbook-python.yaml

Output:

PLAY [web] *****************************************************************************************

TASK [Gathering Facts] *****************************************************************************
[WARNING]: Platform linux on host ubuntu@52.10.253.174 is using the discovered Python interpreter
at /usr/bin/python3.12, but future installation of another Python interpreter could change the
meaning of that path. See https://docs.ansible.com/ansible-
core/2.18/reference_appendices/interpreter_discovery.html for more information.
ok: [ubuntu@52.10.253.174]

TASK [update cache] ********************************************************************************
changed: [ubuntu@52.10.253.174]

TASK [install required software] *******************************************************************
changed: [ubuntu@52.10.253.174]

TASK [create FastAPI dir on remote machine] ********************************************************
changed: [ubuntu@52.10.253.174]

TASK [copy FastAPI to the destination] *************************************************************
changed: [ubuntu@52.10.253.174]

TASK [create virtual env] **************************************************************************
changed: [ubuntu@52.10.253.174]

TASK [inastall fast api on virtual env] ************************************************************
changed: [ubuntu@52.10.253.174]

TASK [Run my application] **************************************************************************
changed: [ubuntu@52.10.253.174]

PLAY RECAP *****************************************************************************************
ubuntu@52.10.253.174       : ok=8    changed=7    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0    

 

Example 5 completed 

 Ansible Galaxy: 

#ansible-galaxy role init role1

role1-playbook.yaml

- hosts: web
become: true
roles:
- role1

\role1\tasks\main.yaml  # default file name can not be changed 

 

- name: install apache to the web remote machine
apt:
name:
- apache2
state: latest

- name: chacke the status of installation
command: systemctl status apache2
register: apache_status
- name: print the status
debug:
msg: "{{apache_status.stdout}}"
- name: replace default page with my custom page
copy:
src: index.html
dest: /var/www/html

- name: Update page with my custom page
copy:
src: update.html
dest: /var/www/html


 



  #ansible-playbook -i inventory.ini Day-2/role1-playbook.yaml --check 

 

 Example 6: 

/var/main.yaml  controls the installation 

 

 

 

 Example 7:  Adding additional conditions 

Print - only OS kernal version is gt 20

 

 

Example 8: 

 


Example 9: Add additional tasks on subtask.yaml and import. subtasks for checking OS family and memory 

in main.yaml - add - 

- import_tasks: subtask.yaml

 

 

 

Example 10: 

Ignoring error  and go to next task. 

 

 

 

 Example 11: using jinja 


 

  

Example 12: using handler 

 

 

 Vaults:  

Thursday, 21 August 2025

Python Notes

 Python Notes 

$ python --version
Python 3.12.3

Python is platform independent 

 python virtual machine:

The Python Virtual Machine (PVM) is an abstract machine and a crucial component of the Python runtime environment. It is responsible for executing Python bytecode, which is a low-level, platform-independent representation of Python source code. 

It supports Virtual Environment :

Create virtual environment : 

$python3 -m venv myvenv #Will install on current folder 

Activate virtual environment: 

$ source myvenv/bin/activate

deactivate #To deactive 

 (myvenv) HostName@Current folder: 

print('Welcome to python training')


PIP:
pip (also known by Python 3's alias pip3) is a package manager (package management system) written in Python and is used to install and manage software packages.

pip install fastapi[all]

 pip freeze > requirements.txt

pip install requirements.txt 

pip list  

 

Variables:
 
username = "Praveen"
city = "Hyderabad"
state = 'TG'
age=40

print(f"Myname is {username} I am from {city} {state} and my age is {age}")

 
data1=int(input('Enter your value-1: '))
data2=int(input('Enter your value-1: '))
print(f"Total: {(data1) + (data2)}")
print(type(data1))
 
Conditions: 
 
if age>30:
print('your allowed to enter')
else:
print('Not Allowed')
  
If Condition with iteration:  

while True:
try:
age = int(input("Enter your age: "))
if 0 <= age <= 101:
break
else:
print("Please enter a valid age between 0 and 101.")
except ValueError:
print("Invalid input! Please enter a number.")
print(f"Your age is: {age}")
 

#################### Array ####################
# array declarations 
 
usernames = ['Bramha','Vishnu','Mahesh']

print(usernames)

# ['Bramha', 'Vishnu', 'Mahesh']

for username in usernames:
print(f"User Details : {username}")

for userindex,username in enumerate(usernames):
print(f"Index : {userindex} --> {username.upper()}")


for userindex,username in enumerate(usernames,start=1):
print(f"Index : {userindex} --> {username.upper()}")
 
Problem - Created and fill array with user input:

# initiating empty array
user_data =[]

data = int(input("How many numbers to add: "))

for i in range(data):
num = int(input(f" Enter number : "))
user_data.append(num)
print(f"values is array: {user_data}")

# calculate even or odd

for num in user_data:
if(num%2==0):
print(f"{num} is even")
else:
print(f"{num} is odd")


# calculate the addition if all numbers
res = 0
for num in user_data:
res +=num
print(f"addition res = {res}")
 
 
# Get Positive input 
 
def get_positive_input(prompt):
while True:
value = int(input(prompt))
if value > 0:
return value
else:
print("Enter a positive value greater than 0.")


data1 = get_positive_input("Enter your value-1: ")
data2 = get_positive_input("Enter your value-2: ")

# Addition
c = data1 + data2
print(f"Addition is: {c}")


#################### Functions ####################
 
# Declare function

def showwelcome():
print("Welcome to the function")

showwelcome()

def calculatedata(x,y):
return print(x+y)

calculatedata(3,2)

def multireturndata(x,y):
return x,y

a,b = multireturndata(2,5)
 
#################### Class #################### 

class user:
def showwelcome(self):
print("Welcome to the class")

def calculatedata(self,x,y):
print(f"Addition is {x+y}")

# using class
uc = user()
uc.showwelcome()
uc.calculatedata(2,3)

#########
 
class user:

def __init__(self): # __int__ - Constructor. It is self called
print('Defult constructor called')

user = user()

#output - Defult constructor called

class user:
def __init__(self,uname,email,city):
self.uname = uname
self.email = email
self.city = city

user = user('Praveen','praveen@mail.com','Hyd')

print(user.uname,user.email,user.city)

#Output - Praveen praveen@mail.com Hyd

class user:
def showcity(self): # Defined the function, not self Constructor
city = input('Enter city : ')
print('city will be called ', city)

user = user() # Loading call
user.showcity() # Calling method

#Output - Enter city : Hyderabad / city will be called Hyderabad


class user:
def __init__(self,uname,email,city):
self.uname = uname
self.email = email
self.city = city
def __str__(self): # This function auto called when your printing object
return f"{self.uname} - {self.email} - {self.city}"
user = user('Praveen','praveen@mail.com','Hyd')

print(user)

#output - Praveen - praveen@mail.com - Hyd

 #####
 
### ribclass.py ### 
 
from abc import ABC,abstractmethod

class RBI(ABC):
@abstractmethod # abstractmethod means mandatory in chaild class
def withdraw(self):
pass
@abstractmethod
def deposit(self):
pass
@abstractmethod
def checkBalance(self):
pass
def openSalaryAccount(self): # No abstractmethod so this function not mandatory in clild
pass
 
 ### ribclass.py closed ###
 
### sbiclass.py ####
 
from rbiclass import RBI # Importing RBI class from rbiclass.py file

class SBI(RBI):
def withdraw(self):
print("withdraw from SBI")
def deposit(self):
print("deposit from SBI")
def checkBalance(self):
print("checkbalance from SBI")
def openFD(self):
print('FD account opened in SBI')
 
### sbiclass.py closed ###
 
### Bankingmail.py ##### 
 
from sbiclass import SBI # Importing SBI class from sbiclass.py file

bank1 = SBI()
bank1.checkBalance()
bank1.openSalaryAccount()
bank1.deposit()
 
### Bankingmail.py closed ##### 
 
# Output - checkbalance from SBI / deposit from SBI 
 
  
 ############ FASTAPI ###########
 
from fastapi import FastAPI

app = FastAPI()

users = ['Admin','Manager','QA']

@app.get("/Welcome")
def Show_Welcome():
return{"Message":"Welcome to FASTAPI"}

# RUN - /Documents/python-ansible/python-training/day-2/fastapi$ uvicorn crudapp:app

@app.get("/loadusers")
def showusers():
return {"message":users}


# Troubleshoot - sudo lsof -i :8000; kill -9 <PID>
 
###########
 
# database.py - File  

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQL_DB = "sqlite:///./mytest.db"

engine = create_engine(
SQL_DB, connect_args={"check_same_thread": False}

)
SessioLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()


def get_connection():
db = SessioLocal()
try:
yield db
finally:
db.close()



-----
# schema.py - file name

from pydantic import BaseModel

# the data you are expecting from the client
class Base(BaseModel):

name: str
sclass: str
section: str


---
# models.py - File name

# schema represenation

from sqlalchemy import Column,String
from .database import Base

class Student(Base):
__tablename__="STUDENT"

name= Column(String,primary_key=True)
sclass= Column(String)
section= Column(String)

class staff(Base):
__tablename__="STAFF"

name= Column(String,primary_key=True)
sclass= Column(String)
section= Column(String)


---
#studentapp.py - File

from fastapi import FastAPI,APIRouter,Depends,status
from fastapi.params import Body
from sqlalchemy.orm import Session
from .. import schema,models
from .. database import engine,get_connection



router= APIRouter(tags=["Student Application"])

@router.post("/addstudent")
def studentRegister(student:schema.Base, db:Session=Depends(get_connection)):
newdata = models.Student(**student.dict())
db.add(newdata)
db.commit()
return {"message":"db created"}

@router.post("/addstaff")
def staffregister(staff:schema.Base, db:Session=Depends(get_connection)):
newdata = models.staff(**staff.dict())
db.add(newdata)
db.commit()
return {"message":"staff created"}

-----
# Crudapp.py - File

from fastapi import FastAPI
from .routers import studentapp

from .database import engine,get_connection
from . import models,schema

# create table in db while loading model class
models.Base.metadata.create_all(bind=engine)
app=FastAPI()

app.include_router(studentapp.router)
 
 
######
 
 
 
 
 
 
 

 

 

 

Key Difference Between List, Array and Tuple

Feature

List

Array

Tuple

Mutability

Mutable

Mutable

Immutable

Data Type

Can store different types

Stores elements of the same type

Can store different types

Ordered

Yes

Yes

Yes

Performance

Slower for numerical operations

Faster for numerical operations

Faster than lists (due to immutability)

Memory Efficiency

Less efficient

More efficient for large data

More memory-efficient than lists

Usage

General-purpose collection

Numerical and homogeneous data

Fixed data, constants

Syntax

[ ]

array()

( )

Indexing

Supported

Supported

Supported


 

  

 

 

Ansible_Notes

   ansible -i inventory.ini -m ping all   # inventory.ini it will ping to the hosts which are in inventory # ansible -i inventory.ini -m pin...