Python : Read and Update helm chart

Recently I was working on a release pipeline where the helm chart of 30+ environments need to be updated in git with the new chart versions from Jenkins input.

Here the helm chart was in yaml format and it was a umbrella chart and individual service chart was needed to be updated from Jenkins.

The umbrella chart file looks like this.

apiVersion: v2
description: Helm chart to deploy application NG
version: 0.0.1
- name: service-a
  version: 0.1.014bf574
  repository: '@helm-repo'
  - application
  enabled: true
- name: service-b
  version: 0.1.014bf575
  repository: '@helm-repo'
  - application
  enabled: true
- name: service-c
  version: 0.1.014bf475
  repository: '@helm-repo'
  - application
  enabled: true
- name: service-d
  version: 0.1.024bf575
  repository: '@helm-repo'
  - application
  enabled: true
- name: service-e
  version: 0.1.014bf559
  repository: '@helm-repo'
  - application
  enabled: true

Here you can see there are 5 dependent services and each version needs to be updated from

I used python module pyyaml.

Here is the code that is used in one stage to achieve this task.

The function takes the input as chart.yaml file path and the subchart and versions in keyword arguments format. Refer the full code from the above link.



python : trace line number with exception

In python we raise exception to catch if anything goes wrong, but sometime with try block we have multiple lines of code and we are not able to track which line exactly throwing the exception.

There is way to catch the line number from which the exception is coming.

try this way:

[code language=”python”]




except Exception as E:

print(‘Error on line {}’.format(sys.exc_info()[-1].tb_lineno), type(E).__name__, E)


Now for any exception, you will get the line number for that also.

pexpect alternative in python for remote connection

We generally use python pexpect module to connect system remotely with ssh and execute our tasks. But sometimes pexpect module is not found to be installed in remote systems which create problems. And this problem can be solved with the python select module with poll.

Here is the sample code that can be used.

chef knife tricks: Add a node in an environment


Sometime during automation of a large deployment process, we have to bootstrap a node , create environment and add the node in that particular environment on the fly.


  1. Bootstraping :

[code language=”ruby”]

knife bootstrap -x root -P password -N node2


2. Create environment dynamically from inside the programme:(python here)

[code language=”python”]

## Create an envtemplate with required values in it

envtemplate = “””

“name”: \””””+envname+”””\”,
“description”: “The master development branch”,
“cookbook_versions”: {
“json_class”: “Chef:Environment”,
“chef_type”: “environment”,
“default_attributes”: {
“required_version”: \””””+appVersion+”””\”

“override_attributes”: {

##write the envtemplate in a file

with open(“/tmp/”+envname+”.json”,”w”) as f:

## Create env from the teplate json file“knife environment from file /tmp/”+envname+”.json”, shell=True)


3. Add the node in the environment:

[code language=”ruby”]

knife exec -E ‘nodes.find(“name:node2”) {|n| n.chef_environment(“env209”); }’



Python : Inplace update json and maintain proper order

Some time we have to read one existing json property file and  update some values inplace.

If we don’t use proper approach, the update may lead to breaking the json structure in the file.

We have to hook the json objects by using OrderedDict of collection module in python for remembering the proper order.

Here old_value is updated with new_value :



“name” : “old_value”



[code language=”python”]

from collections import OrderedDict

propJson = os.path.dirname(os.path.abspath(__file__))+/props.json
if os.path.isfile(propJson):
with open(propJson,r+) as f:
prop = json.load(f, object_hook=OrderedDict)
prop[head][name] = str(new_value)
f.write(json.dumps(prop, f, default=str, indent=4))


Using optparse in python

Sometimes we have to create tools that takes input as argument with certain options. We can create such tool with optparse module of python.

Here is a small example of using this.


[code language=”python”]

from optparse import OptionParser

parser = OptionParser(usage=’usage: %prog [options] arguments’)

parser.add_option(‘-a’,help="setup/cleanup",action="store", dest="action")
parser.add_option(‘-m’,help="email id",action="store", dest="email")
parser.add_option(‘-i’,help="Input json props",action="store", dest="input")
(options, args) = parser.parse_args()


For help, type: ( This will display all the arguments that can be used with their format)

python -h

Usage: [options] arguments

-h, –help show this help message and exit
-a ACTION setup/cleanup
-m EMAIL email id
-i INPUT Input json props

save it in a programme and execute it as :

python -a setup -i file.json -m


Now we can access the above inputs and use them, using below variables inside the programme:

[code language=”python”]





Send mail using Python’s smtplib module

Python has a built in module to send mail to recipient[s] as to,cc,bcc. Here assumption is that : the smtp is configured in localhost (where the script will run).

[code language=”python”]
import socket
import smtplib
from email.mime.text import MIMEText

def SendMail(file,Email,status):
fp = open(file,’rb’)
msg = MIMEText(
msg[‘Subject’] = ‘MULTINODE SETUP :: ‘+status
msg[‘From’] = ‘’
msg[‘to’] = to
msg[‘cc’] = cc

msg[‘bcc’] = bcc
s = smtplib.SMTP(‘localhost’)
s.sendmail(‘’,toaddr ,msg.as_string())





Change tab width in vim

By default, inside vim the tab width is 8 spaces, we can reduce it using below steps.

Create a .vimrc file in ~(home dir) and add below content.  Save it and now try.

filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab

Creating simple progress bar in shell / Python

Progressbar indicates if certain tasks are getting executed and when they completed.

In bash oneliner:

printf “Starting [“;for num in $(seq 50);do printf “#”;sleep 0.5;done;printf “] Successfull”

In Python:

sys.stdout.write(“Starting Operation[“)
for d in range(60):


sys.stdout.write(“]Stoping Operation”)

These can be modified to be used anywhere in codes toprint progressbar.

Read and write json in python

In todays  world json is one of the easiest method of communication to exchange data.

Its used everywhere Cloud APIs, Databases, Configuration files, REST Call.

So below are the steps how to read and write back to a json file using python.

Lets say: test.json contains:

“pro”: “Cloud”,
“fname”: “Priyadarshee”,
“yob”: 1988

To load and read  this file in python:

>>> import json
>>> config = json.loads(open(“test.json”).read())
>>> config
{u’pro’: u’Cloud’, u’yob’: 1988, u’fname’: u’Priyadarshee’}

>>> config[“pro”]


Now adding new key-value pair as well as updating existing pair:

>>> config [“lname”] = “Kumar”
>>> config [“pro”] = “DevOps”
>>> config
{‘lname’: ‘Kumar’, u’pro’: ‘DevOps’, u’yob’: 1988, u’fname’: u’Priyadarshee’}
>>> json.dump(config,open(“test.json”,”w”),indent=4)
>>> config[“pro”]

Here indent = 4, makes the indentation with 4 spaces. It can be adjusted as required.

New test.josn will look like:

cat test.json

“lname”: “Kumar”,
“pro”: “DevOps”,
“yob”: 1988,
“fname”: “Priyadarshee”

We can use this lines in a python script to make a complete code to use as required.