From cbe88626a8190069071acb86b253294376925b4b Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Tue, 7 Nov 2023 12:05:14 +0000 Subject: [PATCH 01/12] feat: add files for day-9 --- Day-09/01-loops.md | 66 ++++++++++++++++++++ Day-09/02-loop-controls.md | 83 +++++++++++++++++++++++++ Day-09/03-for-loop-devops-usecases.md | 67 ++++++++++++++++++++ Day-09/04-while-loop-devops-usecases.md | 66 ++++++++++++++++++++ Day-09/README.md | 1 + 5 files changed, 283 insertions(+) create mode 100644 Day-09/01-loops.md create mode 100644 Day-09/02-loop-controls.md create mode 100644 Day-09/03-for-loop-devops-usecases.md create mode 100644 Day-09/04-while-loop-devops-usecases.md diff --git a/Day-09/01-loops.md b/Day-09/01-loops.md new file mode 100644 index 00000000..b9fdb002 --- /dev/null +++ b/Day-09/01-loops.md @@ -0,0 +1,66 @@ +# Loops in Python (for and while) + +## Introduction + +Loops are a fundamental concept in programming, and they allow you to perform repetitive tasks efficiently. In Python, there are two primary types of loops: "for" and "while." + +## For Loop + +The "for" loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a set of statements for each item in the sequence. The loop continues until all items in the sequence have been processed. + +**Syntax:** + +```python +for variable in sequence: + # Code to be executed for each item in the sequence +``` + +**Example:** + +```python +fruits = ["apple", "banana", "cherry"] +for fruit in fruits: + print(fruit) +``` + +**Output:** + +``` +apple +banana +cherry +``` + +In this example, the loop iterates over the "fruits" list, and in each iteration, the "fruit" variable takes on the value of the current item in the list. + +#### While Loop + +The "while" loop continues to execute a block of code as long as a specified condition is true. It's often used when you don't know in advance how many times the loop should run. + +**Syntax:** + +```python +while condition: + # Code to be executed as long as the condition is true +``` + +**Example:** + +```python +count = 0 +while count < 5: + print(count) + count += 1 +``` + +**Output:** + +``` +0 +1 +2 +3 +4 +``` + +In this example, the "while" loop continues to execute as long as the "count" is less than 5. The "count" variable is incremented in each iteration. diff --git a/Day-09/02-loop-controls.md b/Day-09/02-loop-controls.md new file mode 100644 index 00000000..1f522e20 --- /dev/null +++ b/Day-09/02-loop-controls.md @@ -0,0 +1,83 @@ +# Loop Control Statements (break and continue) + +## Introduction + +Loop control statements are used to modify the behavior of loops, providing greater control and flexibility during iteration. In Python, two primary loop control statements are "break" and "continue." + +## `break` Statement + +The "break" statement is used to exit the loop prematurely. It can be applied to both "for" and "while" loops, allowing you to terminate the loop when a particular condition is met. + +**Example:** + +```python +numbers = [1, 2, 3, 4, 5] +for number in numbers: + if number == 3: + break + print(number) +``` + +**Output:** + +``` +1 +2 +``` + +In this example, the loop stops when it encounters the number 3. + +## `continue` Statement + +The "continue" statement is used to skip the current iteration of the loop and proceed to the next one. It can be used in both "for" and "while" loops, enabling you to bypass certain iterations based on a condition. + +**Example:** + +```python +numbers = [1, 2, 3, 4, 5] +for number in numbers: + if number == 3: + continue + print(number) +``` + +**Output:** + +``` +1 +2 +4 +5 +``` + +In this example, the loop skips the iteration where the number is 3 and continues with the next iteration. + +## Practice Exercise - Automating Log File Analysis + +#### Introduction + +In this practice exercise, we use a "for" loop to automate the analysis of a log file and identify lines containing the word "error." This demonstrates how loops can be used to process data and extract relevant information efficiently. + +**Example:** + +```python +log_file = [ + "INFO: Operation successful", + "ERROR: File not found", + "DEBUG: Connection established", + "ERROR: Database connection failed", +] + +for line in log_file: + if "ERROR" in line: + print(line) +``` + +**Output:** + +``` +ERROR: File not found +ERROR: Database connection failed +``` + +In this exercise, the loop iterates through the "log_file" list and prints lines containing the word "ERROR." \ No newline at end of file diff --git a/Day-09/03-for-loop-devops-usecases.md b/Day-09/03-for-loop-devops-usecases.md new file mode 100644 index 00000000..cf3bb412 --- /dev/null +++ b/Day-09/03-for-loop-devops-usecases.md @@ -0,0 +1,67 @@ +# For Loop DevOps use-cases + +1. **Server Provisioning and Configuration:** + + DevOps engineers use "for" loops when provisioning multiple servers or virtual machines with the same configuration. For example, when setting up monitoring agents on multiple servers: + + ```bash + servers=("server1" "server2" "server3") + for server in "${servers[@]}"; do + configure_monitoring_agent "$server" + done + ``` + +2. **Deploying Configurations to Multiple Environments:** + + When deploying configurations to different environments (e.g., development, staging, production), DevOps engineers can use a "for" loop to apply the same configuration changes to each environment: + + ```bash + environments=("dev" "staging" "prod") + for env in "${environments[@]}"; do + deploy_configuration "$env" + done + ``` + +3. **Backup and Restore Operations:** + + Automating backup and restore operations is a common use case. DevOps engineers can use "for" loops to create backups for multiple databases or services and later restore them as needed. + + ```bash + databases=("db1" "db2" "db3") + for db in "${databases[@]}"; do + create_backup "$db" + done + ``` + +4. **Log Rotation and Cleanup:** + + DevOps engineers use "for" loops to manage log files, rotate logs, and clean up older log files to save disk space. + + ```bash + log_files=("app.log" "access.log" "error.log") + for log_file in "${log_files[@]}"; do + rotate_and_cleanup_logs "$log_file" + done + ``` + +5. **Monitoring and Reporting:** + + In scenarios where you need to gather data or perform checks on multiple systems, a "for" loop is handy. For example, monitoring server resources across multiple machines: + + ```bash + servers=("server1" "server2" "server3") + for server in "${servers[@]}"; do + check_resource_utilization "$server" + done + ``` + +6. **Managing Cloud Resources:** + + When working with cloud infrastructure, DevOps engineers can use "for" loops to manage resources like virtual machines, databases, and storage across different cloud providers. + + ```bash + instances=("instance1" "instance2" "instance3") + for instance in "${instances[@]}"; do + resize_instance "$instance" + done + ``` diff --git a/Day-09/04-while-loop-devops-usecases.md b/Day-09/04-while-loop-devops-usecases.md new file mode 100644 index 00000000..c0736b2c --- /dev/null +++ b/Day-09/04-while-loop-devops-usecases.md @@ -0,0 +1,66 @@ +# While Loop DevOps Usecases + +DevOps engineers often use "while" loops in various real-time use cases to automate, monitor, and manage infrastructure and deployments. Here are some practical use cases from a DevOps engineer's perspective: + +1. **Continuous Integration/Continuous Deployment (CI/CD) Pipeline:** + + DevOps engineers often use "while" loops in CI/CD pipelines to monitor the deployment status of applications. They can create a "while" loop that periodically checks the status of a deployment or a rolling update until it completes successfully or fails. For example, waiting for a certain number of pods to be ready in a Kubernetes deployment: + + ```bash + while kubectl get deployment/myapp | grep -q 0/1; do + echo "Waiting for myapp to be ready..." + sleep 10 + done + ``` + +2. **Provisioning and Scaling Cloud Resources:** + + When provisioning or scaling cloud resources, DevOps engineers may use "while" loops to wait for the resources to be fully provisioned and ready. For instance, waiting for an Amazon EC2 instance to become available: + + ```bash + while ! aws ec2 describe-instance-status --instance-ids i-1234567890abcdef0 | grep -q "running"; do + echo "Waiting for the EC2 instance to be running..." + sleep 10 + done + ``` + +3. **Log Analysis and Alerting:** + + DevOps engineers can use "while" loops to continuously monitor logs for specific events or errors and trigger alerts when a certain condition is met. For example, tailing a log file and alerting when an error is detected: + + ```bash + while true; do + if tail -n 1 /var/log/app.log | grep -q "ERROR"; then + send_alert "Error detected in the log." + fi + sleep 5 + done + ``` + +4. **Database Replication and Data Synchronization:** + + DevOps engineers use "while" loops to monitor database replication and ensure data consistency across multiple database instances. The loop can check for replication lag and trigger corrective actions when necessary. + + ```bash + while true; do + replication_lag=$(mysql -e "SHOW SLAVE STATUS\G" | grep "Seconds_Behind_Master" | awk '{print $2}') + if [ "$replication_lag" -gt 60 ]; then + trigger_data_sync + fi + sleep 60 + done + ``` + +5. **Service Health Monitoring and Auto-Recovery:** + + DevOps engineers can use "while" loops to continuously check the health of services and automatically trigger recovery actions when services become unhealthy. + + ```bash + while true; do + if ! check_service_health; then + restart_service + fi + sleep 30 + done + ``` + diff --git a/Day-09/README.md b/Day-09/README.md index e69de29b..d31a16aa 100644 --- a/Day-09/README.md +++ b/Day-09/README.md @@ -0,0 +1 @@ +# Loops \ No newline at end of file From 3ba1f9358f1e9ec53a640defdf31e247e992641d Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Wed, 8 Nov 2023 12:31:13 +0000 Subject: [PATCH 02/12] feat: add files for day-10 --- Day-10/01-convert-string-to-list.py | 1 + Day-10/02-main-construct.py | 10 ++++++++++ Day-10/03-list-files-in-folders.py | 25 +++++++++++++++++++++++++ Day-10/README.md | 1 + README.md | 2 +- 5 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 Day-10/01-convert-string-to-list.py create mode 100644 Day-10/02-main-construct.py create mode 100644 Day-10/03-list-files-in-folders.py diff --git a/Day-10/01-convert-string-to-list.py b/Day-10/01-convert-string-to-list.py new file mode 100644 index 00000000..c3a6e442 --- /dev/null +++ b/Day-10/01-convert-string-to-list.py @@ -0,0 +1 @@ +folder_paths = input("Enter a list of folder paths separated by spaces: ").split() \ No newline at end of file diff --git a/Day-10/02-main-construct.py b/Day-10/02-main-construct.py new file mode 100644 index 00000000..95a84c5d --- /dev/null +++ b/Day-10/02-main-construct.py @@ -0,0 +1,10 @@ +def main(): + folder_paths = input("Enter a list of folder paths separated by spaces: ").split() + print(folder_paths) + + # Print elements in the list + #for folder_path in folder_paths: + # print(folder_path) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Day-10/03-list-files-in-folders.py b/Day-10/03-list-files-in-folders.py new file mode 100644 index 00000000..7710c4bb --- /dev/null +++ b/Day-10/03-list-files-in-folders.py @@ -0,0 +1,25 @@ +import os + +def list_files_in_folder(folder_path): + try: + files = os.listdir(folder_path) + return files, None + except FileNotFoundError: + return None, "Folder not found" + except PermissionError: + return None, "Permission denied" + +def main(): + folder_paths = input("Enter a list of folder paths separated by spaces: ").split() + + for folder_path in folder_paths: + files, error_message = list_files_in_folder(folder_path) + if files: + print(f"Files in {folder_path}:") + for file in files: + print(file) + else: + print(f"Error in {folder_path}: {error_message}") + +if __name__ == "__main__": + main() diff --git a/Day-10/README.md b/Day-10/README.md index e69de29b..c85d0b1a 100644 --- a/Day-10/README.md +++ b/Day-10/README.md @@ -0,0 +1 @@ +# Lists Part-2 \ No newline at end of file diff --git a/README.md b/README.md index 655c5a89..884680f0 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ - List comprehensions. - Nested lists and advanced list operations. - Practice exercises and examples: - - Example: Parsing a complex configuration file with nested lists. + - Example: Print list of files in the list of folders provided ## Day 11: Working with Dictionaries and Sets - Dictionaries and key-value pairs. From 53a9830e82e9a0e29b07c0ac55ac01d275c26278 Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Thu, 16 Nov 2023 09:36:30 +0000 Subject: [PATCH 03/12] feat: add files for day-11 --- Day-11/01-dictionaries.md | 37 +++++++++++++++ Day-11/02-sets.md | 60 +++++++++++++++++++++++++ Day-11/03-lists-vs-sets.md | 92 ++++++++++++++++++++++++++++++++++++++ Day-11/04-practicals.md | 29 ++++++++++++ Day-11/04-practicals.py | 15 +++++++ Day-11/README.md | 1 + 6 files changed, 234 insertions(+) create mode 100644 Day-11/01-dictionaries.md create mode 100644 Day-11/02-sets.md create mode 100644 Day-11/03-lists-vs-sets.md create mode 100644 Day-11/04-practicals.md create mode 100644 Day-11/04-practicals.py diff --git a/Day-11/01-dictionaries.md b/Day-11/01-dictionaries.md new file mode 100644 index 00000000..baedd1f0 --- /dev/null +++ b/Day-11/01-dictionaries.md @@ -0,0 +1,37 @@ +# Dictionaries + +## Overview: +A dictionary in Python is a data structure that allows you to store and retrieve values using keys. It is also known as a hashmap or associative array in other programming languages. Dictionaries are implemented as hash tables, providing fast access to values based on their keys. + +## Creating a Dictionary: +```python +my_dict = {'name': 'John', 'age': 25, 'city': 'New York'} +``` + +## Accessing Values: +```python +print(my_dict['name']) # Output: John +``` + +## Modifying and Adding Elements: +```python +my_dict['age'] = 26 # Modifying a value +my_dict['occupation'] = 'Engineer' # Adding a new key-value pair +``` + +## Removing Elements: +```python +del my_dict['city'] # Removing a key-value pair +``` + +## Checking Key Existence: +```python +if 'age' in my_dict: + print('Age is present in the dictionary') +``` + +## Iterating Through Keys and Values: +```python +for key, value in my_dict.items(): + print(key, value) +``` \ No newline at end of file diff --git a/Day-11/02-sets.md b/Day-11/02-sets.md new file mode 100644 index 00000000..e76ea735 --- /dev/null +++ b/Day-11/02-sets.md @@ -0,0 +1,60 @@ +# Sets and Set Operations + +#### Overview: +A set in Python is an unordered collection of unique elements. It is useful for mathematical operations like union, intersection, and difference. + +#### Creating a Set: +```python +my_set = {1, 2, 3, 4, 5} +``` + +#### Adding and Removing Elements: +```python +my_set.add(6) # Adding an element +my_set.remove(3) # Removing an element +``` + +#### Set Operations: +```python +set1 = {1, 2, 3, 4} +set2 = {3, 4, 5, 6} + +union_set = set1.union(set2) # Union of sets +intersection_set = set1.intersection(set2) # Intersection of sets +difference_set = set1.difference(set2) # Difference of sets +``` + +#### Subset and Superset: +```python +is_subset = set1.issubset(set2) # Checking if set1 is a subset of set2 +is_superset = set1.issuperset(set2) # Checking if set1 is a superset of set2 +``` + +### Practice Exercises and Examples + +#### Example: Managing a Dictionary of Server Configurations and Optimizing Retrieval + +##### Scenario: +Suppose you are managing server configurations using a dictionary. + +```python +server_config = { + 'server1': {'ip': '192.168.1.1', 'port': 8080, 'status': 'active'}, + 'server2': {'ip': '192.168.1.2', 'port': 8000, 'status': 'inactive'}, + 'server3': {'ip': '192.168.1.3', 'port': 9000, 'status': 'active'} +} +``` + +##### Function for Retrieval: +```python +def get_server_status(server_name): + return server_config.get(server_name, {}).get('status', 'Server not found') +``` + +##### Example Usage: +```python +server_name = 'server2' +status = get_server_status(server_name) +print(f"{server_name} status: {status}") +``` + diff --git a/Day-11/03-lists-vs-sets.md b/Day-11/03-lists-vs-sets.md new file mode 100644 index 00000000..35e81023 --- /dev/null +++ b/Day-11/03-lists-vs-sets.md @@ -0,0 +1,92 @@ +# Lists vs. Sets + +## Lists + +- **Ordered Collection:** + - Lists are ordered collections of elements. The order in which elements are added is preserved. + - Elements can be accessed by their index. + + ```python + my_list = [1, 2, 3, 4, 5] + print(my_list[0]) # Output: 1 + ``` + +- **Mutable:** + - Lists are mutable, meaning you can modify their elements after creation. + + ```python + my_list[1] = 10 + ``` + +- **Allows Duplicate Elements:** + - Lists can contain duplicate elements. + + ```python + my_list = [1, 2, 2, 3, 4] + ``` + +- **Use Cases:** + - Use lists when you need an ordered collection with the ability to modify elements. + +## Sets + +- **Unordered Collection:** + - Sets are unordered collections of unique elements. The order in which elements are added is not preserved. + - Elements cannot be accessed by their index. + + ```python + my_set = {1, 2, 3, 4, 5} + ``` + +- **Mutable:** + - Sets are mutable, meaning you can add and remove elements after creation. + + ```python + my_set.add(6) + ``` + +- **No Duplicate Elements:** + - Sets do not allow duplicate elements. If you try to add a duplicate, it won't raise an error, but the set won't change. + + ```python + my_set = {1, 2, 2, 3, 4} # Results in {1, 2, 3, 4} + ``` + +- **Use Cases:** + - Use sets when you need an unordered collection of unique elements, and you want to perform set operations like union, intersection, and difference. + +### Common Operations: + +- **Adding Elements:** + - Lists use `append()` or `insert()` methods. + - Sets use `add()` method. + +- **Removing Elements:** + - Lists use `remove()`, `pop()`, or `del` statement. + - Sets use `remove()` or `discard()` methods. + +- **Checking Membership:** + - Lists use the `in` operator. + - Sets use the `in` operator as well, which is more efficient for sets. + +```python +# Lists +if 3 in my_list: + print("3 is in the list") + +# Sets +if 3 in my_set: + print("3 is in the set") +``` + +### Choosing Between Lists and Sets + +- **Use Lists When:** + - You need to maintain the order of elements. + - Duplicate elements are allowed. + - You need to access elements by index. + +- **Use Sets When:** + - Order doesn't matter. + - You want to ensure unique elements. + - You need to perform set operations like union, intersection, or difference. diff --git a/Day-11/04-practicals.md b/Day-11/04-practicals.md new file mode 100644 index 00000000..bfb5b9ef --- /dev/null +++ b/Day-11/04-practicals.md @@ -0,0 +1,29 @@ +# Practice Exercises and Examples + +## Example: Managing a Dictionary of Server Configurations and Optimizing Retrieval + +### Scenario: +Suppose you are managing server configurations using a dictionary. + +```python +server_config = { + 'server1': {'ip': '192.168.1.1', 'port': 8080, 'status': 'active'}, + 'server2': {'ip': '192.168.1.2', 'port': 8000, 'status': 'inactive'}, + 'server3': {'ip': '192.168.1.3', 'port': 9000, 'status': 'active'} +} +``` + +### Function for Retrieval: +```python +def get_server_status(server_name): + return server_config.get(server_name, {}).get('status', 'Server not found') +``` + +### Example Usage: +```python +server_name = 'server2' +status = get_server_status(server_name) +print(f"{server_name} status: {status}") +``` + +In this example, the function `get_server_status` optimizes the retrieval of the server status by using the `get` method and providing a default value if the server name is not found. \ No newline at end of file diff --git a/Day-11/04-practicals.py b/Day-11/04-practicals.py new file mode 100644 index 00000000..9d0aeb9e --- /dev/null +++ b/Day-11/04-practicals.py @@ -0,0 +1,15 @@ +# Server configurations dictionary +server_config = { + 'server1': {'ip': '192.168.1.1', 'port': 8080, 'status': 'active'}, + 'server2': {'ip': '192.168.1.2', 'port': 8000, 'status': 'inactive'}, + 'server3': {'ip': '192.168.1.3', 'port': 9000, 'status': 'active'} +} + +# Retrieving information +def get_server_status(server_name): + return server_config.get(server_name, {}).get('status', 'Server not found') + +# Example usage +server_name = 'server2' +status = get_server_status(server_name) +print(f"{server_name} status: {status}") diff --git a/Day-11/README.md b/Day-11/README.md index e69de29b..1ff79071 100644 --- a/Day-11/README.md +++ b/Day-11/README.md @@ -0,0 +1 @@ +# Dictionaries and Sets \ No newline at end of file From dab0b271cc08880725cab8fcbde0d87eae281edc Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Mon, 20 Nov 2023 20:42:37 +0530 Subject: [PATCH 04/12] demo --- Day-11/04-demo-github-integration.py | 33 ++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Day-11/04-demo-github-integration.py diff --git a/Day-11/04-demo-github-integration.py b/Day-11/04-demo-github-integration.py new file mode 100644 index 00000000..d6c96ff9 --- /dev/null +++ b/Day-11/04-demo-github-integration.py @@ -0,0 +1,33 @@ +# Program to demonstrate integration with GitHub to fetch the +# details of Users who created Pull requests(Active) on Kubernetes Github repo. + +import requests + +# URL to fetch pull requests from the GitHub API +url = f'https://api.github.com/repos/kubernetes/kubernetes/pulls' + +# Make a GET request to fetch pull requests data from the GitHub API +response = requests.get(url) # Add headers=headers inside get() for authentication + +# Only if the response is successful +if response.status_code == 200: + # Convert the JSON response to a dictionary + pull_requests = response.json() + + # Create an empty dictionary to store PR creators and their counts + pr_creators = {} + + # Iterate through each pull request and extract the creator's name + for pull in pull_requests: + creator = pull['user']['login'] + if creator in pr_creators: + pr_creators[creator] += 1 + else: + pr_creators[creator] = 1 + + # Display the dictionary of PR creators and their counts + print("PR Creators and Counts:") + for creator, count in pr_creators.items(): + print(f"{creator}: {count} PR(s)") +else: + print(f"Failed to fetch data. Status code: {response.status_code}") From a30ed9fe3307fec7e04fe3f30a74eec04a25587c Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Tue, 21 Nov 2023 16:33:00 +0530 Subject: [PATCH 05/12] Update README.md --- README.md | 34 ++++++++++------------------------ 1 file changed, 10 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 884680f0..cf8ca024 100644 --- a/README.md +++ b/README.md @@ -68,53 +68,39 @@ - Practice exercises and examples: - Example: Managing a dictionary of server configurations and optimizing retrieval. -## Day 12: Functions and Modules -- Introduction to functions in Python. -- Writing functions and function parameters. -- Return values and modular code. +## Day 12: Python Libraries for DevOps (Part 1) +- Introduction to File Operations and Boto3. +- Automating File operations. - Practice exercises and examples: - - Example: Creating a function to automate server status checks. + - Example: Update a server resources in the server.conf file up on external notification. -## Day 13: Functions and Modules (Part 2) -- Advanced function topics (recursion, lambda functions). -- Function libraries and built-in functions. -- Practice exercises and examples: - - Example: Developing a library of custom functions for DevOps automation. - -## Day 14: Python Libraries for DevOps (Part 1) -- Introduction to external libraries like Paramiko, Fabric, and Boto3. -- Automating SSH connections with Paramiko. -- Running commands on remote servers. -- Practice exercises and examples: - - Example: Using Paramiko to create a secure remote backup solution. - -## Day 15: Python Libraries for DevOps (Part 2) +## Day 13: Python Libraries for DevOps (Part 2) - Using Fabric for remote task automation. - AWS automation with Boto3. - Managing EC2 instances, S3 buckets, and more. - Practice exercises and examples: - - Example: Creating a Fabric script for deploying applications to remote servers. + - Example: Creating a aws script for deploying applications to remote servers. -## Day 16: Working with RESTful APIs +## Day 14: Working with RESTful APIs - Introduction to RESTful APIs. - Making HTTP requests using Python. - Parsing JSON responses and error handling. - Practice exercises and examples: - Example: Developing a script to monitor RESTful API endpoints for your DevOps tools. -## Day 17: Data Serialization and Configuration Files +## Day 15: Data Serialization and Configuration Files - Serializing and deserializing data (JSON, YAML). - Managing configuration data. - DevOps use cases for configuration files. - Practice exercises and examples: - Example: Building a configuration manager to handle application settings in JSON format. -## Day 18: Automation with Cron Jobs +## Day 16: Automation with Cron Jobs - Scheduling automated tasks using cron. - Creating Python scripts for scheduled automation. - Handling periodic tasks and reports. - Practice exercises and examples: - Example: Using cron and Python to schedule regular backups of your data. -## Day 19: Python Interview Questions & Answers +## Day 17: Python Interview Questions & Answers From 412686033460e0aed3dd6f72f45071af183b06b6 Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Tue, 21 Nov 2023 12:18:42 +0000 Subject: [PATCH 06/12] update files for day-12 --- Day-12/README.md | 0 Day-12/server.conf | 17 +++++++++++++++++ Day-12/update_server.py | 25 +++++++++++++++++++++++++ README.md | 4 ++-- 4 files changed, 44 insertions(+), 2 deletions(-) delete mode 100644 Day-12/README.md create mode 100644 Day-12/server.conf create mode 100644 Day-12/update_server.py diff --git a/Day-12/README.md b/Day-12/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/Day-12/server.conf b/Day-12/server.conf new file mode 100644 index 00000000..e9d46d83 --- /dev/null +++ b/Day-12/server.conf @@ -0,0 +1,17 @@ +# Server Configuration File + +# Network Settings +PORT = 8080 +MAX_CONNECTIONS=600 +TIMEOUT = 30 + +# Security Settings +SSL_ENABLED = true +SSL_CERT = /path/to/certificate.pem + +# Logging Settings +LOG_LEVEL = INFO +LOG_FILE = /var/log/server.log + +# Other Settings +ENABLE_FEATURE_X = true \ No newline at end of file diff --git a/Day-12/update_server.py b/Day-12/update_server.py new file mode 100644 index 00000000..65677891 --- /dev/null +++ b/Day-12/update_server.py @@ -0,0 +1,25 @@ +def update_server_config(file_path, key, value): + # Read the existing content of the server configuration file + with open(file_path, 'r') as file: + lines = file.readlines() + + # Update the configuration value for the specified key + with open(file_path, 'w') as file: + for line in lines: + # Check if the line starts with the specified key + if key in line: + # Update the line with the new value + file.write(key + "=" + value + "\n") + else: + # Keep the existing line as it is + file.write(line) + +# Path to the server configuration file +server_config_file = 'server.conf' + +# Key and new value for updating the server configuration +key_to_update = 'MAX_CONNECTIONS' +new_value = '600' # New maximum connections allowed + +# Update the server configuration file +update_server_config(server_config_file, key_to_update, new_value) diff --git a/README.md b/README.md index cf8ca024..23ecf82a 100644 --- a/README.md +++ b/README.md @@ -68,13 +68,13 @@ - Practice exercises and examples: - Example: Managing a dictionary of server configurations and optimizing retrieval. -## Day 12: Python Libraries for DevOps (Part 1) +## Day 12: Python Tasks for DevOps (Part 1) - File Operations - Introduction to File Operations and Boto3. - Automating File operations. - Practice exercises and examples: - Example: Update a server resources in the server.conf file up on external notification. -## Day 13: Python Libraries for DevOps (Part 2) +## Day 13: Python Tasks for DevOps (Part 2) - Using Fabric for remote task automation. - AWS automation with Boto3. - Managing EC2 instances, S3 buckets, and more. From 70f5215b3065007069175df9a7bdcac44b13ce05 Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Mon, 27 Nov 2023 16:05:06 +0000 Subject: [PATCH 07/12] add files for day-14 --- Day-14/examples/create-jira.py | 54 ++++++++++++++++++++++++++++++++ Day-14/examples/list_projects.py | 28 +++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 Day-14/examples/create-jira.py create mode 100644 Day-14/examples/list_projects.py diff --git a/Day-14/examples/create-jira.py b/Day-14/examples/create-jira.py new file mode 100644 index 00000000..e9618ad0 --- /dev/null +++ b/Day-14/examples/create-jira.py @@ -0,0 +1,54 @@ +# This code sample uses the 'requests' library: +# http://docs.python-requests.org +import requests +from requests.auth import HTTPBasicAuth +import json + +url = "https://veeramallaabhishek.atlassian.net/rest/api/3/issue" + +API_TOKEN = "" + +auth = HTTPBasicAuth("", API_TOKEN) + +headers = { + "Accept": "application/json", + "Content-Type": "application/json" +} + +payload = json.dumps( { + "fields": { + "description": { + "content": [ + { + "content": [ + { + "text": "My first jira ticket", + "type": "text" + } + ], + "type": "paragraph" + } + ], + "type": "doc", + "version": 1 + }, + "project": { + "key": "AB" + }, + "issuetype": { + "id": "10006" + }, + "summary": "First JIRA Ticket", + }, + "update": {} +} ) + +response = requests.request( + "POST", + url, + data=payload, + headers=headers, + auth=auth +) + +print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": "))) \ No newline at end of file diff --git a/Day-14/examples/list_projects.py b/Day-14/examples/list_projects.py new file mode 100644 index 00000000..93ecf2ca --- /dev/null +++ b/Day-14/examples/list_projects.py @@ -0,0 +1,28 @@ +# This code sample uses the 'requests' library: +# http://docs.python-requests.org +import requests +from requests.auth import HTTPBasicAuth +import json + +url = "https://veeramallaabhishek.atlassian.net/rest/api/3/project" + +API_TOKEN="" + +auth = HTTPBasicAuth("", API_TOKEN) + +headers = { + "Accept": "application/json" +} + +response = requests.request( + "GET", + url, + headers=headers, + auth=auth +) + +output = json.loads(response.text) + +name = output[0]["name"] + +print(name) \ No newline at end of file From 1cc122bb6ee06447e6778949c826720900b752b2 Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Thu, 30 Nov 2023 13:24:07 +0530 Subject: [PATCH 08/12] Update README.md --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 23ecf82a..f32309c8 100644 --- a/README.md +++ b/README.md @@ -62,38 +62,38 @@ - Practice exercises and examples: - Example: Print list of files in the list of folders provided -## Day 11: Working with Dictionaries and Sets +## Day 11: Working with Dictionaries and Sets (Project-1) - Dictionaries and key-value pairs. - Sets and set operations. - Practice exercises and examples: - Example: Managing a dictionary of server configurations and optimizing retrieval. -## Day 12: Python Tasks for DevOps (Part 1) - File Operations +## Day 12: Python Tasks for DevOps (Part 1) - File Operations (Project-2) - Introduction to File Operations and Boto3. - Automating File operations. - Practice exercises and examples: - Example: Update a server resources in the server.conf file up on external notification. -## Day 13: Python Tasks for DevOps (Part 2) +## Day 13: Python Tasks for DevOps (Part 2) (Project-3) - Using Fabric for remote task automation. - AWS automation with Boto3. - Managing EC2 instances, S3 buckets, and more. - Practice exercises and examples: - Example: Creating a aws script for deploying applications to remote servers. -## Day 14: Working with RESTful APIs +## Day 14: Github-JIRA intergration Project - (Project-4) - Introduction to RESTful APIs. - Making HTTP requests using Python. - Parsing JSON responses and error handling. - Practice exercises and examples: - - Example: Developing a script to monitor RESTful API endpoints for your DevOps tools. + - Example: Write a Python API which listens on a github comment and creates a ticket in JIRA. -## Day 15: Data Serialization and Configuration Files -- Serializing and deserializing data (JSON, YAML). -- Managing configuration data. -- DevOps use cases for configuration files. +## Day 15: Github-JIRA intergration Project - (Project-4) - (Part-2) +- Introduction to Flask. +- Write your first API in python. +- How to handle API calls and deploy your API to a server. - Practice exercises and examples: - - Example: Building a configuration manager to handle application settings in JSON format. + - Example: Write a Python API which listens on a github comment and creates a ticket in JIRA. ## Day 16: Automation with Cron Jobs - Scheduling automated tasks using cron. From b5e1c516754107dad67bf1b9396e17f383349b12 Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Thu, 30 Nov 2023 16:53:09 +0000 Subject: [PATCH 09/12] add files for day-15 --- Day-14/README.md | 1 + Day-15/README.md | 1 + Day-15/examples/hello-world.py | 10 ++++++ Day-15/github-jira.py | 65 ++++++++++++++++++++++++++++++++++ 4 files changed, 77 insertions(+) create mode 100644 Day-15/examples/hello-world.py create mode 100644 Day-15/github-jira.py diff --git a/Day-14/README.md b/Day-14/README.md index e69de29b..9b1a3075 100644 --- a/Day-14/README.md +++ b/Day-14/README.md @@ -0,0 +1 @@ +# Github-JIRA intergration Project \ No newline at end of file diff --git a/Day-15/README.md b/Day-15/README.md index e69de29b..781a8c42 100644 --- a/Day-15/README.md +++ b/Day-15/README.md @@ -0,0 +1 @@ +# Github-JIRA intergration Project - (Part-2) \ No newline at end of file diff --git a/Day-15/examples/hello-world.py b/Day-15/examples/hello-world.py new file mode 100644 index 00000000..3d602756 --- /dev/null +++ b/Day-15/examples/hello-world.py @@ -0,0 +1,10 @@ +from flask import Flask + +app = Flask(__name__) + +@app.route('/') +def hello_world(): + return 'Hello, World!' + +if __name__ == '__main__': + app.run("0.0.0.0") diff --git a/Day-15/github-jira.py b/Day-15/github-jira.py new file mode 100644 index 00000000..c5003813 --- /dev/null +++ b/Day-15/github-jira.py @@ -0,0 +1,65 @@ +# This code sample uses the 'requests' library: +# http://docs.python-requests.org +import requests +from requests.auth import HTTPBasicAuth +import json +from flask import Flask + +app = Flask(__name__) + +# Define a route that handles GET requests +@app.route('/createJira', methods=['POST']) +def createJira(): + + url = "https://veeramallaabhishek.atlassian.net/rest/api/3/issue" + + API_TOKEN="" + + auth = HTTPBasicAuth("", API_TOKEN) + + headers = { + "Accept": "application/json", + "Content-Type": "application/json" + } + + payload = json.dumps( { + "fields": { + "description": { + "content": [ + { + "content": [ + { + "text": "Order entry fails when selecting supplier.", + "type": "text" + } + ], + "type": "paragraph" + } + ], + "type": "doc", + "version": 1 + }, + "project": { + "key": "AB" + }, + "issuetype": { + "id": "10006" + }, + "summary": "Main order flow broken", + }, + "update": {} + } ) + + + response = requests.request( + "POST", + url, + data=payload, + headers=headers, + auth=auth + ) + + return json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")) + +if __name__ == '__main__': + app.run(host='0.0.0.0', port=5000) \ No newline at end of file From 0d962b852e0b2a909da49fb1f4332e221f01cb4b Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Mon, 11 Dec 2023 20:30:42 +0530 Subject: [PATCH 10/12] Update README.md --- README.md | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index f32309c8..0dc09cb5 100644 --- a/README.md +++ b/README.md @@ -95,12 +95,8 @@ - Practice exercises and examples: - Example: Write a Python API which listens on a github comment and creates a ticket in JIRA. -## Day 16: Automation with Cron Jobs -- Scheduling automated tasks using cron. -- Creating Python scripts for scheduled automation. -- Handling periodic tasks and reports. -- Practice exercises and examples: - - Example: Using cron and Python to schedule regular backups of your data. +## Day 16: Python Interview Questions & Answers +- Beginner and intermediate Level ## Day 17: Python Interview Questions & Answers - +- Advanced Level From 7a2982acfe5e3b03de4db121366332e0e6140ce7 Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Mon, 11 Dec 2023 20:48:57 +0530 Subject: [PATCH 11/12] Update README.md --- Day-16/README.md | 244 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 244 insertions(+) diff --git a/Day-16/README.md b/Day-16/README.md index e69de29b..d8728f2d 100644 --- a/Day-16/README.md +++ b/Day-16/README.md @@ -0,0 +1,244 @@ +# Interview Questions (Beginner and Intermediate) + +## Describe a real-world example of how you used Python to solve a DevOps challenge. + +- Here you can talk about the projects that we did in this series + - GitHub Webhooks + - JIRA integration + - File Operations + +## Discuss the challenges that you faced while using Python for DevOps and how did you overcome it. + +- Here you can mention about a challenge that you faced while implementating a Python project for DevOps that we learnt. + +## How can you secure your Python code and scripts? + +- Handle any sensetive information using Input variables, command line arguments or env vars. + +## Explain the difference between mutable and immutable objects. + +In Python, mutable objects can be altered after creation, while immutable objects cannot be changed once created. For instance: + +Mutable objects like lists can be modified: + +``` +my_list = [1, 2, 3] +my_list[0] = 0 # Modifying an element in the list +print(my_list) # Output: [0, 2, 3] +``` + +Immutable objects like tuples cannot be altered: + +``` +my_tuple = (1, 2, 3) +# Attempting to change a tuple will result in an error +# my_tuple[0] = 0 +``` + +## Differentiate between list and tuple in Python. + +Lists are mutable and typically used for storing collections of items that can be changed, while tuples are immutable and commonly used to store collections of items that shouldn't change. Examples: + +List: + +``` +my_list = [1, 2, 3] +my_list.append(4) # Modifying by adding an element +print(my_list) # Output: [1, 2, 3, 4] +``` + +Tuple: + +``` +my_tuple = (1, 2, 3) +# Attempting to modify a tuple will result in an error +# my_tuple.append(4) +``` + +## Explain the use of virtualenv. + +Virtualenv creates isolated Python environments, allowing different projects to use different versions of packages without conflicts. Example: + +Creating a virtual environment: + +### Creating a virtual environment named 'myenv' +virtualenv myenv + +Activating the virtual environment: + +### On Windows +``` +myenv\Scripts\activate +``` + +### On Unix or MacOS +``` +source myenv/bin/activate +``` + +## What are decorators in Python? + +Decorators modify the behavior of functions. They take a function as an argument, add some functionality, and return another function without modifying the original function's code. Example: + +Defining a simple decorator: + +``` +def my_decorator(func): + def wrapper(): + print("Something is happening before the function is called.") + func() + print("Something is happening after the function is called.") + return wrapper + +@my_decorator +def say_hello(): + print("Hello!") + +say_hello() +``` + +## How does exception handling work in Python? + +Exception handling in Python uses try, except, else, and finally blocks. Example: + +Handling division by zero exception: + +``` +try: + result = 10 / 0 +except ZeroDivisionError: + print("Division by zero is not allowed.") +else: + print("Division successful:", result) +finally: + print("Execution completed.") +``` + +## What's the difference between append() and extend() for lists? + +append() adds a single element to the end of a list, while extend() adds multiple elements by appending elements from an iterable. Example: + +Using append(): +``` +my_list = [1, 2, 3] +my_list.append(4) +print(my_list) # Output: [1, 2, 3, 4] +``` + +Using extend(): + +``` +my_list = [1, 2, 3] +my_list.extend([4, 5]) +print(my_list) # Output: [1, 2, 3, 4, 5] +``` + +## Explain the use of lambda functions in Python. + +Lambda functions are anonymous functions used for short tasks. Example: + +Defining and using a lambda function: + +``` +square = lambda x: x**2 +print(square(5)) # Output: 25 +``` + +## What are the different types of loops in Python? + +Python has for loops and while loops. + +Example: + +Using for loop: +``` +for i in range(5): + print(i) +``` + +Using while loop: +``` +i = 0 +while i < 5: + print(i) + i += 1 +``` + +## Explain the difference between == and is operators. + +The == operator compares the values of two objects, while the is operator checks if two variables point to the same object in memory. + +Example: + +Using ==: + +``` +a = [1, 2, 3] +b = [1, 2, 3] +print(a == b) # Output: True (because values are equal) +``` + +Using is: + +``` +a = [1, 2, 3] +b = a +print(a is b) # Output: True (because they reference the same object) +``` + +## What is the use of the pass keyword? + +The pass keyword is a no-operation placeholder used when a statement is syntactically needed but no action is required. Example: + +Using pass: +``` +def placeholder_function(): + pass # To be implemented later +``` + +## What is the difference between global and local variables? + +Global variables are defined outside functions and can be accessed anywhere in the code, while local variables are defined inside functions and are only accessible within that function's scope. Example: + +Using a global variable: +``` +global_var = 10 + +def my_function(): + print(global_var) + +my_function() # Output: 10 +``` + +Using a local variable: + +``` +def my_function(): + local_var = 5 + print(local_var) + +my_function() # Output: 5 +# Attempting to access local_var outside the function will result in an error +``` + +## Explain the difference between open() and with open() statement. + +open() is a built-in function used to open a file and return a file object. +However, it's crucial to manually close the file using file_object.close(). +Conversely, with open() is a context manager that automatically handles file closure, ensuring clean-up even if exceptions occur. + +Example: +``` +file = open('example.txt', 'r') +content = file.read() +file.close() +``` + +Using with open(): +``` +with open('example.txt', 'r') as file: + content = file.read() +# File is automatically closed when the block exits +``` + + From 14518aeb0a2e08f470f60892bbc83b0b7ba8b5eb Mon Sep 17 00:00:00 2001 From: Abhishek Veeramalla Date: Wed, 3 Apr 2024 21:34:24 +0530 Subject: [PATCH 12/12] simple python app --- simple-python-app/app.py | 10 ++++++++++ simple-python-app/requirements.txt | 2 ++ 2 files changed, 12 insertions(+) create mode 100644 simple-python-app/app.py create mode 100644 simple-python-app/requirements.txt diff --git a/simple-python-app/app.py b/simple-python-app/app.py new file mode 100644 index 00000000..0c9d9e60 --- /dev/null +++ b/simple-python-app/app.py @@ -0,0 +1,10 @@ +from flask import Flask + +app = Flask(__name__) + +@app.route('/') +def hello_world(): + return 'Hello, World!' + +if __name__ == '__main__': + app.run(debug=True, host='0.0.0.0', port=8000) \ No newline at end of file diff --git a/simple-python-app/requirements.txt b/simple-python-app/requirements.txt new file mode 100644 index 00000000..fdceace4 --- /dev/null +++ b/simple-python-app/requirements.txt @@ -0,0 +1,2 @@ +Flask==2.1.0 +Werkzeug==2.2.2 \ No newline at end of file