Using Python to automate devops activities
Git Hooks
- Git Hooks are scripts that Git automatically executes after certain events (commit, merging, pushing)
- Types:
- Client
- Server
- Client Side Hooks:
- pre-commit
- prepare-commit-msg
- commit-msg
- post-commit
Activity: Our organization wants to check that the commit message contains feature id or defect id.
- The commit message should in the following format
<defect-id|feature-id>: <message>
- First part is check the basic structure
defect id => defect-xxxxx
defect-12345
feature id => feature-xxxxx
feature-12345
-
input => commit message
-
output => exit with 0 (success) or 1 (failure)
-
We will have
.git/hooks -
Regular expressions in python Refer Here
-
commit message validation
#!/usr/bin/env python
import sys
import re
def validate_commit_message(commit_message):
"""This method validates the commit message
Returns:
True if valid and false otherwise
"""
pattern = r'^(feature|defect)-\d{5}:'
# fetch defect or feature id
# send the request to azuredevops or jira with
# defect to verify if it actual defect or not
return re.match(pattern,commit_message)
def main():
"""This function will read the file and call validate message
exits with 0 if valid commit message otherwise exits with 1
"""
commit_message_path = sys.argv[1]
with open(commit_message_path, "r") as file:
commit_message = file.read().strip()
if validate_commit_message(commit_message):
sys.exit(0)
else:
print(
"commit message has to be in the form of <defect-id|feature-id>: <message>"
)
sys.exit(1)
if __name__ == "__main__":
main()
Calling Jenkins Jobs from python
- Requirement: Whenever a ticket is raised in your organization in service now, you are supposed to run jenkins job
- Whenever a ticket is raised in service now it will call aws lambda function,
- Run jenkins job and show the success or failure information.
- Calling jenkins job from api Refer Here
- Ensure requests library is installed
pip install requests
- Refer Here for code changes
