Python is a high-level, interpreted programming language widely used in DevOps and Cloud automation for its simplicity, readability, and extensive ecosystem of libraries.
In DevOps, Python is used to:
Answer:
Python is popular because it’s:
boto3, os, subprocess, and requests for automation.Example use case:
Automate EC2 instance creation, parse server logs, or trigger Jenkins builds — all with Python scripts.
Answer:
math, os, boto3).__init__.py file.Example:
import os
print(os.getcwd()) # Get current working directory
In DevOps:
Modules help organize automation code, such as separating cloud utilities, CI/CD scripts, and logging functions.
Answer:
deploy.py).Example:
deploy.py may import aws_utils.py to reuse AWS-related functions.
This separation improves code reusability and modularity in automation projects.
Answer:
# Write to a file
with open('log.txt', 'w') as f:
f.write("Deployment startedn")# Read from a fileIn DevOps:
Used to store logs, read configurations, or parse reports from tools like Jenkins or Docker.
Answer:
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("Task completed")
Why important:
Automation scripts often interact with APIs or cloud services — proper exception handling prevents crashes and ensures smooth error recovery.
Answer:
| Type | Mutable | Ordered | Syntax |
|---|---|---|---|
| List | Yes | Yes | [1,2,3] |
| Tuple | No | Yes | (1,2,3) |
| Dict | Yes | Key-based | {'env': 'prod'} |
In automation:
Answer:
Functions encapsulate reusable logic and reduce code duplication.
Example:
def start_instance(instance_id):
print(f"Starting EC2 instance: {instance_id}")
In real-world DevOps:
Functions help modularize automation scripts — e.g., one for creating EC2 instances, another for tagging, and one for cleanup.
Answer:
PIP is Python’s package manager used to install third-party libraries.
Example:
pip install boto3
In CI/CD:
PIP is used in pipeline stages to install dependencies dynamically (e.g., AWS SDK, requests, Flask).
Answer:
Virtual environments isolate dependencies for different projects.
Example:
python3 -m venv env
source env/bin/activate
Why important:
Prevents dependency conflicts between different automation projects or CI/CD pipelines.
Answer:
python3 script.py
You can also make it executable:
chmod +x script.py
./script.py
In automation workflows, scripts are often executed within Jenkins or Ansible playbooks to perform deployment steps.
Answer:
Using the boto3 library — AWS SDK for Python.
Example:
import boto3
ec2 = boto3.client('ec2')response = ec2.describe_instances()Real-world use:
Automate EC2 start/stop, S3 bucket management, IAM role creation, or CloudWatch log analysis.
Answer:
Use the subprocess module:
import subprocess
result = subprocess.run([‘ls’, ‘-l’], capture_output=True, text=True)
print(result.stdout)
In DevOps:
Run Docker, kubectl, or Terraform commands programmatically within pipelines.
Answer:
requests.Example:
import requests
url = “http://jenkins.local/job/BuildApp/build”
requests.post(url, auth=(‘admin’, ‘password’))
In CI/CD:
Python automates complex build flows or external integrations Jenkinsfile alone can’t handle.
Answer:
import json
data = ‘{“env”: “prod”, “version”: “1.2”}’
parsed = json.loads(data)
print(parsed[‘env’])
Use case:
Parse API responses from AWS or Kubernetes to extract dynamic values for automation scripts.
Answer:
Using the requests library:
import requests
response = requests.get(‘https://api.github.com’)
print(response.status_code)
In DevOps:
Used for monitoring API health, triggering webhooks, or calling REST APIs in automation flows.
Answer:
import logging
logging.basicConfig(filename=’app.log’, level=logging.INFO)
logging.info(‘Deployment started’)
logging.error(‘Failed to deploy app’)
Why:
Structured logging helps trace automation workflows and troubleshoot CI/CD failures easily.
Answer:
Options:
Example:
import schedule, time
def backup():
print(“Backing up data…”)
schedule.every().day.at(“00:00”).do(backup)
while True:
schedule.run_pending()
time.sleep(1)
Use case:
Nightly backups, log cleanup, or AWS instance start/stop scripts.
Answer:
import os
env = os.getenv(‘ENVIRONMENT’, ‘dev’)
print(f”Running in {env} mode”)
Why:
In Jenkins or GitHub Actions, environment variables control script behavior dynamically (e.g., environment, region).
Answer:
Using the Docker SDK:
import docker
client = docker.from_env()
for container in client.containers.list():
print(container.name)
Use case:
Automate container builds, cleanups, and monitoring within DevOps pipelines.
Answer:
import mysql.connector
db = mysql.connector.connect(
host=”localhost”,
user=”admin”,
password=”password”,
database=”devops”
)
cursor = db.cursor()
cursor.execute(“SELECT * FROM users”)
In DevOps:
Used to automate DB health checks, schema updates, or report generation.
Answer:
boto3 for AWS interactions.Example structure:
aws_automation/
│── ec2_utils.py
│── s3_utils.py
│── main.py
│── config.yaml
Outcome:
Reusable, scalable automation framework for multi-account cloud management.
Answer:
asyncio.Example:
import threading
def deploy_server(id):
print(f”Deploying server {id}”)
threads = []
for i in range(5):
t = threading.Thread(target=deploy_server, args=(i,))
threads.append(t)
t.start()
This approach drastically reduces script execution time during large-scale automation.
Answer:
session = boto3.Session(profile_name='prod')
In interviews:
Emphasize avoiding plain-text keys and following AWS security best practices.
Answer:
Using the kubernetes Python client:
from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
for pod in v1.list_pod_for_all_namespaces().items:
print(pod.metadata.name)
Use case:
Automate pod monitoring, deployments, or scaling via Python instead of kubectl.
Answer:
Using asyncio and aiohttp:
import aiohttp, asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
urls = [“https://api.github.com”, “https://aws.amazon.com”]
tasks = [fetch(session, url) for url in urls]
await asyncio.gather(*tasks)
asyncio.run(main())
Why:
Improves performance for scripts interacting with multiple APIs simultaneously.
Answer:
Compare live AWS configuration from boto3 with Terraform state outputs or YAML definitions.
Example use case:
A script runs daily to detect mismatched configurations (e.g., missing tags, unauthorized EC2s) and sends alerts via Slack.
Answer:
Dockerfile Example:
FROM python:3.11
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python3", "main.py"]
Why:
Running scripts in containers ensures consistency across environments — from local to Jenkins or AWS Lambda.
Answer:
def lambda_handler(event, context):
return {"status": "Success", "message": "Automation triggered"}
Use case:
Serverless automation for daily backups, tagging, or security scans.
Q: You were asked to automate the daily cleanup of unused EC2 instances. How did you do it?
Answer (STAR):
boto3 to check instance metrics via CloudWatch.Q: Describe a time you used Python to improve your CI/CD pipeline.
Answer (STAR):