Home Navigation

Monday, 16 March 2026

Multiple github account management with ssh

Sometimes it is hard to manage multiple GitHub accounts and deal with conflicts when cloning and pushing code. For example, if we have three accounts, we can follow these steps:

Example:

ssh-keygen -t ed25519 -C "personal@email.com" -f ~/.ssh/github_personal
ssh-keygen -t ed25519 -C "work@email.com" -f ~/.ssh/github_work
ssh-keygen -t ed25519 -C "school@email.com" -f ~/.ssh/github_school

You will get:

~/.ssh/github_personal
~/.ssh/github_personal.pub

~/.ssh/github_work
~/.ssh/github_work.pub

~/.ssh/github_school
~/.ssh/github_school.pub

Upload each .pub key to the correct GitHub account.

Clean SSH config

Edit:

nano ~/.ssh/config

Add:

Host github.com-personal
HostName github.com
User git
IdentityFile ~/.ssh/github_personal
IdentitiesOnly yes

Host github.com-work
HostName github.com
User git
IdentityFile ~/.ssh/github_work
IdentitiesOnly yes

Host github.com-school
HostName github.com
User git
IdentityFile ~/.ssh/github_school
IdentitiesOnly yes

Create a repo folder structure

Example:

~/dev/personal/
~/dev/work/
~/dev/school/

Clone repos normally but change the host

Personal:

git clone git@github.com-personal:<owner>/<repo-name>.git

Work:

git clone git@github.com-work:<owner>/<repo-name>.git

School:

git clone git@github.com-school:<owner>/<repo-name>.git

Automatic Git identity (the magic part)

Edit your global git config:

nano ~/.gitconfig

Add:

[user]
name = Your Name
email = personal@email.com

[includeIf "gitdir:~/dev/work/"]
path = ~/.gitconfig-work

[includeIf "gitdir:~/dev/school/"]
path = ~/.gitconfig-school

Work Git config

Create:

nano ~/.gitconfig-work
[user]
name = Your Work Name
email = work@email.com

School Git config

nano ~/.gitconfig-school
[user]
name = Your Name
email = school@email.com

Result

FolderGitHub account used
~/dev/personalpersonal
~/dev/workwork
~/dev/schoolschool

So when you:

cd ~/dev/work/project
git commit

Git automatically uses your work email + SSH key.

No switching accounts. No confusion.

Test SSH connections:

ssh -T git@github.com-personal
ssh -T git@github.com-work
ssh -T git@github.com-school


Friday, 31 January 2025

How to Create a Self-Signed Certificate: A Step-by-Step Guide

Create Self-Signed Certificate

In today's digital landscape, secure communication is essential. Whether you're setting up a development environment, testing SSL/TLS configurations, or securing internal services, a self-signed certificate can be a handy solution. This guide walks you through creating a self-signed certificate using OpenSSL.

What is a Self-Signed Certificate?

A self-signed certificate is an SSL/TLS certificate that is not issued by a trusted Certificate Authority (CA). Instead, it is generated and signed by the same entity that intends to use it. While not suitable for public-facing websites, self-signed certificates are useful for testing, internal applications, and development environments.

Prerequisites

Before generating a self-signed certificate, ensure you have OpenSSL installed. Most Linux and macOS systems include OpenSSL by default. Windows users can download it from OpenSSL's official website.

To check if OpenSSL is installed, run the following command:

openssl version

If OpenSSL is installed, you should see the version number.

Step 1: Generate a Private Key

The first step in creating a self-signed certificate is generating a private key. This key is essential for encrypting and decrypting information.

Run the following command to generate a 2048-bit RSA private key:

Generate a private key with a passphrase:

openssl genpkey \
-algorithm RSA \
-out private.key -aes256

You will be prompted to enter a passphrase. Choose a strong passphrase and remember it.

Generate a private key without a passphrase:

openssl genpkey \
-algorithm RSA \
-out private.key

Step 2: Create a Certificate Signing Request (CSR)

A CSR contains information about your organization and domain. Generate a CSR using the following command:

openssl req -new -key private.key -out certificate.csr

You will be prompted to enter details such as:

  • Country Name (e.g., US)
  • State or Province Name (e.g., California)
  • Locality Name (e.g., San Francisco)
  • Organization Name (e.g., MyCompany Inc.)
  • Organizational Unit Name (e.g., IT Department)
  • Common Name (e.g., example.com)
  • Email Address

Ensure the Common Name (CN) matches the domain or IP where the certificate will be used.

Step 3: Generate the Self-Signed Certificate

Use the following command to create a self-signed certificate valid for 365 days:

openssl x509 -req \
-days 365 \
-in certificate.csr \
-signkey private.key \
-out selfsigned.crt

Step 4: Create a Wildcard Certificate (Optional)

If you need a wildcard certificate to cover all subdomains (e.g., *.example.com), modify the CSR by specifying a wildcard CN:


openssl req -new \
-key private.key \
-out wildcard.csr \
-subj "/C=US/ST=California/L=San Francisco/O=MyCompany Inc./OU=IT Department/CN=*.example.com"

Then generate the self-signed wildcard certificate:

openssl x509 -req \
-days 365 \
-in wildcard.csr \
-signkey private.key -out wildcard.crt

Step 5: Verify the Certificate

To check the details of your certificate, run:

openssl x509 -in selfsigned.crt -noout -text

This command displays the certificate information, including validity and issuer details.

Step 6: Convert to PKCS#12 (Optional)

If you need a .pfx file for Windows or other applications, convert the certificate as follows:

openssl pkcs12 -export -out selfsigned.pfx -inkey private.key -in selfsigned.crt

You will be asked to set an export password for the .pfx file.

Conclusion

You've successfully created a self-signed SSL certificate using OpenSSL! This certificate can now be used for testing, securing internal applications, or local development. However, for production environments, always use a certificate from a trusted Certificate Authority (CA) to ensure security and trust.

If you have any questions or need further guidance, feel free to ask in the comments!

Thursday, 17 October 2024

Steps to Get Image Pull Secret for IBM Container Registry

Steps to Get Image Pull Secret for IBM Container Registry

  1. Log in to IBM Cloud CLI: If you haven't already, install the IBM Cloud CLI and log in to your IBM Cloud account:


    ibmcloud login
  2. Install the Container Registry Plugin: If you don’t have the Container Registry plugin installed, install it:


    ibmcloud plugin install container-registry
  3. Log in to IBM Container Registry: After installing the plugin, log in to the IBM Cloud Container Registry:

    ibmcloud cr login
  4. Generate API Key (Optional, but preferred for automation): Create an API key to securely authenticate with the IBM Container Registry. You can use it later to create the image pull secret in OpenShift:

    ibmcloud iam api-key-create MyAPIKey \ -d "API key for OpenShift pull" --file my-api-key.json
  5. Create an Image Pull Secret in OpenShift: Now, create the secret that allows OpenShift to pull images from the IBM Container Registry. You can use your IBM Cloud account credentials or an API key for authentication.

    For API Key authentication:

    oc create secret docker-registry ibm-cr-secret \ --docker-server=icr.io \ --docker-username=iamapikey \ --docker-password=$(cat my-api-key.json | jq -r .apikey) \ --docker-email=<your-email>

    Replace:

    • icr.io with the appropriate IBM Container Registry region endpoint (us.icr.io, eu.icr.io, jp.icr.io, etc.).
    • <your-email> with your email address.

    For IBM Cloud Username/Password authentication:

    oc create secret docker-registry ibm-cr-secret \
    --docker-server=icr.io \ --docker-username=iamapikey \ --docker-password=$(ibmcloud iam oauth-tokens | awk '{print $4}') \ --docker-email=<your-email>
  6. Link the Image Pull Secret to a Service Account: To use this secret, associate it with the default service account in your project:

    oc secrets link default ibm-cr-secret --for=pull
  7. Ensure the secret is linked to the default service account:

    oc get serviceaccount default -o yaml
  8. Deploy the Container: Once the image pull secret is in place, you can deploy the container in OpenShift by creating a deployment configuration or pod that uses the image from IBM Container Registry:

    apiVersion: apps/v1 kind: Deployment metadata: name: my-app spec: replicas: 1 selector: matchLabels: app: my-app template: metadata: labels: app: my-app spec: containers: - name: my-container image: icr.io/namespace/my-image:tag imagePullSecrets: - name: ibm-cr-secret

After this, OpenShift will pull the image from IBM Cloud Container Registry using the credentials stored in the secret.

Region Endpoints for IBM Container Registry

Choose the correct container registry endpoint based on your region:

  • us.icr.io - US South
  • eu.icr.io - Frankfurt
  • jp.icr.io - Tokyo

Make sure to replace the region in the docker-server and image URL accordingly.

podman version 5.1.2 push image got Error: unexpected EOF

With podman version 5.1.2  when I tried to push a large image specially 3.5 GB I was having issue with Error: unexpected EOF. My platform is Mac book pro.

After some googling and debugging figured it was a memory issue. By default assigned memory in podman virtual machine is not enough.  So I had to manually assign a bit more memory to the podman virtual machine.

Here are the steps to that solved the issue


podman machine stop

podman machine rm
podman machine init -m 4096 

podman machine start

Happy learning!

Thursday, 11 April 2024

Openshift: Attach volume failed: CSINode does not contain driver vpc.block.csi.ibm.io

I encountered an error in the OpenShift cluster. It said that 'AttachVolume.Attach' failed because the CSINode 10.240.0.9 does not contain the 'vpc.block.csi.ibm.io' driver. As a result, all the pods connected to the volume were failing and couldn't start the pod.


After researching, I discovered that the Block Storage for VPC addon was on an older version, 5.0, and it was in critical status. All I needed to do was update the addon from version 5.0 to 5.1


Here are the commands to fix the issue,

Check addOn status

ibmcloud ks cluster addon ls -c <OpenShift cluster Id/Name>

OK

Name                   Version              Health State   Health Status   

vpc-block-csi-driver   5.0* (5.1 default)   critical       Addon Unsupported. For more info: http://ibm.biz/addon-state (H1509)

Update addOn version

 ibmcloud ks cluster addon update vpc-block-csi-driver -c <OpenShift cluster Id/Name> --version 5.1



Friday, 27 October 2023

Setting up Artifactory repository for python pip package

Generate token

  • Login to Artifactory
  • Go to top right corner and click on the menu Edit profile
  • Then Click on Generate an Identity token
  • Copy the generated token

Setting up the token

  • From the command terminal open pip.config file, location ~/.pip/pip.config
  • add an entry like below

[global]

index-url = https://<ARTIFACTORY_USER>:<ARTIFACTORY_API_KEY>@<ARTIFACTORY_URL>/<ARTIFACTORY_REPO>

Friday, 7 July 2023

Connect to elasticsearch using python

 Based on your elasticsearch version, you have to install the Python Elasticsearch Client.

I am using elasticsearch version 7.10

# Elasticsearch 7.x
elasticsearch>=7.0.0,<8.0.0

# Elasticsearch 6.x
elasticsearch>=6.0.0,<7.0.0

# Elasticsearch 5.x
elasticsearch>=5.0.0,<6.0.0

# Elasticsearch 2.x
elasticsearch>=2.0.0,<3.0.0

Prepare your environment

python3 -m venv backend
source backend/bin/activate
pip3 install elasticsearch===7.10.1

Code

from elasticsearch import Elasticsearch
from elasticsearch.exceptions import RequestError

# Create an instance of Elasticsearch with TLS options
es = Elasticsearch(
'https://<user>:<password>@<host>:<port>',
ca_certs='<cert_file>'
)

print("=======================================================")

info = es.info()
print(info)
print("=======================================================")

# Test the connection and create an index
index_name = 'my_index'

try:
es.indices.create(index=index_name)
print(f"Index '{index_name}' created successfully.")
except RequestError as e:
if e.error == 'resource_already_exists_exception':
print(f"Index '{index_name}' already exists.")
else:
print(f"An error occurred while creating index '{index_name}': {e}")


document = {
'title': 'Example Document',
'content': 'This is the content of the document.'
}

# Add the document to the index
response = es.index(index=index_name, body=document)
print("=======================================================")
print(response)

Run

python3 app.py


Enjoy!


Ref: https://elasticsearch-py.readthedocs.io/en/v7.10.1/

https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/getting-started-python.html




Wednesday, 26 April 2023

A simple script to build and push docker image to an OpenShift internal registry

echo "building the gradle project" ./gradlew clean bootJar echo "building docker image" TAG=1.0.1 NAME=image-name NAMESPACE=namespace-name docker build -t $NAME:$TAG . echo "pushing image to openshift internal registry" export REGISTRY=$(oc get routes -n openshift-image-registry -o jsonpath='{.items[0].spec.host}') echo $(oc whoami -t) | docker login $REGISTRY -u $(oc whoami) --password-stdin docker tag $NAME:$TAG $REGISTRY/$NAMESPACE/$NAME:$TAG docker push $REGISTRY/$NAMESPACE/$NAME:$TAG

Thursday, 1 September 2022

Push image to OpenShift internal registry

Follow the below steps


Enable internal registry

oc patch configs.imageregistry.operator.openshift.io/cluster --patch '{"spec":{"defaultRoute":true}}' --type=merge

Get the internal registry 

oc get routes -n openshift-image-registry


Export the internal registry to an environmental variable

export REGISTRY=<The Registry URL you get from previous Command>

Login to the internal registry 

echo $(oc whoami -t) | docker login $REGISTRY -u $(oc whoami) --password-stdin

Build the docker image like below

docker build -t myimage:latest .

Tag your docker image with OpenShift registry

docker tag dashapp-grpc:latest $REGISTRY/<NAMESPACE>/myimage:latest

Push your docker image to OpenShift Internal Registry

docker push $REGISTRY/<NAMESPACE>/myimage:latest

Tag your image with OpenShift ImageStream

oc tag <NAMESPACE>/myimage:latest myimage:latest

List your ImageStream tags

oc get is

Tuesday, 7 June 2022

Kubernetes basics and cheatsheet

Before we start about Kubernetes let us first cover some of the basics of containers and what is the benefits of containerization. 

A container is an executable package of software that includes everything needed to run it. Containerization is the packaging of software code with just the operating system (OS) libraries and dependencies required to run the code to create a single lightweight executable—called a container—that runs consistently on any infrastructure

Executable unit of software

  • Encapsulate everything necessary to run
  • Can be run anywhere

OS Virtualization:

  • Isolates process
  • Control resources allocated to those process

Small, fast, and portable

  • Doesn’t include guest OS in every instance
  • Leverages host OS

Benefits of container:

  • Portability
  • Agility: rapid application development
  • Speed: 
    • Lightweight
    • Don’t include guest os
    • Spin up quickly and horizontally scalable
  • Fault isolation
    • The failure of one container does not affect the continued operation of any other containers
  • Efficiency / cost effective
  • Ease of management
  • Security

The Open Container Initiative (OCI), established in June 2015 by Docker and other industry leaders, is promoting common, minimal, open standards and specifications around container technology.
The ecosystem is standardizing on containerd and other alternatives like CoreOS rkt, Mesos Containerizer, LXC Linux Containers, OpenVZ, and crio-d.


Docker is a platform for building and running container. A Docker file serves as the blueprint for an image.
  • Image: An image is an immutable file that contains everything necessary to run an application.
  • Container is a running image
  • Each docker instruction creates a new read-only layer. A writable layer is added when an image is run as a container.
Note: The main difference between ADD and COPY in docker file is that COPY can only copy local files or directory, whereas ADD can also add files from remote URLs
CMD is the default execution command generally stays at the last in docker file.
Naming: hostname/repository:tag

Kubernetes is an open-source container orchestration system for automating software deployment, scaling, and management. Google originally designed Kubernetes, but the Cloud Native Computing Foundation now maintains the project. Wikipedia

Managing the lifecycle of containers, especially in large, dynamic environments
  • Provisioning and deployment
  • Availability
  • Scaling
  • Scheduling to infrastructure
  • Rolling updates
  • Health checks
Kubernetes as “a portable, extensible, open-source platform for managing containerized workloads and services that facilitates both declarative configuration and automation.It has a large, rapidly growing ecosystem. Kubernetes services, support, and tools are widely available.”

Kubernetes is not a
  • Paas
  • Does not limit the types of applications
  • Does not deploy source code or build application
  • Does not provide-built-in middleware, databases, or other services
A Kubernetes cluster is a set of nodes that run containerized application. When you deploy Kubernetes you get a cluster. In Kubernetes cluster consists of two types of nodes,
  • Control plane ( Master node)
  • Nodes ( Worker nodes)


Control plane ( Master node):
It makes decisions about the cluster and detects and responds to events in the cluster.
  • Kubernetes API: All communication in the cluster utilizes this API.
  • Kubernetes scheduler:
    • The Kubernetes scheduler assigns newly created Pods to nodes. This means that the scheduler determines where your workloads should run within the cluster.
  • etcd:  
    • a highly available key value store that contains all the cluster data. When you tell Kubernetes to deploy your application, that deployment configuration is stored in etcd. Etcd is thus the source of truth for the state in a Kubernetes cluster, and the system works
  • Kubernetes controller manager: 
    • The Kubernetes controller manager runs all the controller processes that monitor the cluster state and ensure that the actual state of a cluster matches the desired state. 
  • Cloud controller manager:
    • Runs controllers that interact with the underlying cloud providers.These controllers effectively link clusters into a cloud provider’s API. Since Kubernetes is open source software and would ideally be adopted by a variety of cloud providers and organizations, it strives to be as cloud-agnostic as possible.
Kubernetes worker nodes
  • Nodes: 
    • Nodes are the worker machines in a Kubernetes cluster. In other words, user applications are run on nodes. Nodes can be a physical machine or a virtual machine. Managed by control plane contains the services to run applications.
  • Kube proxy:
    • Network proxy
    • Maintains network rules that allow communication to pods
  • Kubelet:
    • Communicates with the API server
    • Ensures that Pods and their associated containers are running
    • Reports to the control plan on health and status
A control loop is defined as a non-terminating loop that regulates the state of a system.

Kubernetes Objects are persistent entities in Kubernetes."Persistent" means that when you create an object, Kubernetes continually works to ensure that that object exists in the system, until and unless you modify or remove that object.
  • Persistent entities in kubernetes
  • Define the desired state of your workload
  • Use the Kubernetes API to work with them, like kubectl
Kubernetes objects consist of two main fields.
  • The first is the object "spec," which is provided by the user. The spec dictates the desired state for this object.
  • The second field is the "status," which is provided by Kubernetes. The status describes the current state of the object—its actual state as opposed to its desired state. The status is updated if at any time the status of the object changes.
  1. Namespaces: namespaces can be used to provide logical separation of a cluster into virtual clusters.
  2. Labels: Labels are key/value pairs that can be attached to objects in order to identify those objects.
  3. Pods: Simplest unit in Kubernetes, represents process running in cluster, encapsulate a container, POD serve to scale an app horizontal
  4. ReplicaSet: A ReplicaSet is a group of identical Pods that are running. a ReplicaSet encapsulates a Pod definition and adds additional information needed to replicate it.
  5. Deployment: Deployment object, a higher-level concept that in turn manages ReplicaSets, A Deployment is an object that provides updates for both Pods and ReplicaSets.
    • provides updates for pods and replicates
    • Runs multiple replicas of your application
    • Suitable for stateless applications
    • updates triggers a rollout
  • Autoscaling:
    • ReplicaSet works with a set number of pods
    • Horizontal Pod Autoscaler (HPA) enables scaling up and down as needed.
      • Kind: HorizontalPodAutoScaler
      • And in spec you define the attribute
      • Behind the scene it uses replicaSet to create object
    • Can configure based on desired state of CPU, memory etc
  • Rolling Update:
    • ReplicaSet and Autoscaling are important to minimize and service interruption
    • Rolling Update are a way to roll out app changes in an automated and controlled fashion throughout your pods
    • Rolling updates give us a way to publish changes to our applications without Noticeable interruptions for the user.
    • Additionally, rolling updates give us a way to roll back any changes to the application
    • Kubectl rollout status deployments/hello-kubernets
    • Kubectl rollout undo deployments/hello-kubernetes
ConfigMaps give us a way to provide configuration data to pods and deployments so we don't have to hard-code that data in the application code. You can also reuse these ConfigMaps and Secrets for multiple deployments.
  • Used to provide configuration for deployments
  • Reusable across deployments
  • Created in a couple of different ways:
    • using string literals
    • Using an existing properties or key=value file
    • Providing a configMap yaml descriptor file. Both the first and second ways can help us create such a file.
    • Configmap is not for sensitive data and it has only 1MB Storage limit
$kubectl create ConfigMap my-config --from-literal=MESSAGE="hello world config map"
$kubectl cm my-config --from-file=my.properties

A Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key. Such information might otherwise be put in a Pod specification or in a container image. Using a Secret means that you don't need to include confidential data in your application code.

$kubectl create secret generic api-creds --from-literal=key=mycred

Why do we need services?
Service - responsible for enabling network access to a set of pods. Each pod has its own IP address. Pods are ephemeral and destroyed frequently. Each time pods recreate a new IP is get assigned.

Whereas service has stable IP address, load balancing. It is loosely coupled and helps routing within and outside cluster. Selector helps to identify to which pods to forward the request. Pods are identified via selectors a key value pair.

ClusterIp: Exposes the Service on a cluster-internal IP. Choosing this value makes the Service only reachable from within the cluster. This is the default ServiceType. You cannot make requests to service (pods) from outside the cluster.
  • Inter service communication within the cluster. For example, communication between the front-end and back-end components of your app.
  • K8s create endpoints object same name as service to keep track of which pods are the members/endpoints of the service. $kubectl get endpoints -n myapp



Headless Services: Client wants to communicate with one specific POD instead of going via services. 
Pods want to talk directly with specific pod like database master and slave. It is mostly used of StatefulSet Object. 
            DNS lookup for service – returns single IP address in Cluster IP for example. Set ClusterIP to None returns Pod IP address instead. No Cluster IP is assigned to the POD.



NodePort Services: Exposes the Service on each Node's IP at a static port (the NodePort). A ClusterIP Service, to which the NodePort Service routes, is automatically created. You'll be able to contact the NodePort Service, from outside the cluster, by requesting <NodeIP>:<NodePort>

Node port must be in the range of 30000–32767. Manually allocating a port to the service is optional. If it is undefined, Kubernetes will automatically assign one.

it is not so secured as you are opening a service port using a clusterIP.

Use Cases
  • When you want to enable external connectivity to your service.
  • Using a NodePort gives you the freedom to set up your own load balancing solution, to configure environments that are not fully supported by Kubernetes, or even to expose one or more nodes’ IPs directly.
  • Prefer to place a load balancer above your nodes to avoid node failure.

Load balancer: Exposes the Service externally using a cloud provider's load balancer. NodePort and ClusterIP Services, to which the external load balancer routes, are automatically created.  It exposes the Service externally using a cloud provider’s load balancer.

LoadBalancer is an extension of NodePort service. Do not use nodePort service to expose to external. Configure Ingress or LoadBalancer for production environments.


ExternalName
  • Services of type ExternalName map a Service to a DNS name, not to a typical selector such as my-service.
  • You specify these Services with the `spec.externalName` parameter.
  • It maps the Service to the contents of the externalName field (e.g. foo.bar.example.com), by returning a CNAME record with its value.
  • No proxying of any kind is established.
Use Cases
  • This is commonly used to create a service within Kubernetes to represent an external datastore like a database that runs externally to Kubernetes.
  • You can use that ExternalName service (as a local service) when Pods from one namespace to talk to a service in another namespace.

Ingress: Kubernetes Ingress is an API object that provides routing rules to manage external users' access to the services in a Kubernetes cluster, typically via HTTPS/HTTP. With Ingress, you can easily set up rules for routing traffic without creating a bunch of Load Balancers or exposing each service on the node

Ingress exposes HTTP and HTTPS routes from outside the cluster to services within the cluster. Traffic routing is controlled by rules defined on the Ingress resource.




Host:
  • A valid domain addresses
  • Map domain name to Node’s IP address which is the entry point
  • Or you can map the domain to an external entry point IP address
Ingress Controller:
  • Evaluates all the rules
  • Manages redirections
  • Entrypoint to cluster
  • Exposes HTTP/HTTPS routes for a cluster  
  • Provides route-based load balancing 
  • Can terminate TLS 
  • Provides name-based virtual hosting


Kubernetes cheatsheet commands: