Let's Talk DevOps

Real-World DevOps, Real Solutions

Tag: Kubernetes

  • Kubernetes quickstarts – AKS, EKS, GKE

    There has been a lot of inquiries about how to get started quickly with what is commonly referred as the hyperscalers. Let’s dive in for a super quick primer!

    All of these quickstarts assume the reader has accounts in each service with the appropriate rights and in most cases the reader needs to have the client installed.

    Starting with Google Kubernetes Engine (GKE)

    export NAME="$(whoami)-$RANDOM"
    export ZONE="us-west2-a"
    gcloud container clusters create "${NAME}" --zone ${ZONE} --num-nodes=1
    glcoud container clusters get-credentials "${NAME}" --zone ${ZONE}

    Moving on to Azure Kubernetes Service (AKS)

    export NAME="$(whoami)-$RANDOM"
    export AZURE_RESOURCE_GROUP="${NAME}-group"
    az group create --name "${AZURE_RESOURCE_GROUP}" -l westus2
    az aks create --resource-group "${AZURE_RESOURCE_GROUP}" --name "${NAME}"
    az aks get-credentials --resource-group "${AZURE_RESOURCE_GROUP}" --name "${NAME}"

    For Elastic Kubernetes Service (EKS)

    export NAME="$(whoami)-$RANDOM"
    eksctl create cluster --name "${NAME}"

    As you can see setting up these clusters is very simple. Now that you have a cluster what are you going to do with it? Ensure you’ve installed the tools needed to manage the cluster. You’ll want to get the credentials from each copy into ~/{user}/.kube/config (except with eksctl as it copies the kubeconfig to the appropriate place automagically). To manipulate the cluster, install kubectl with your favorite package manager and to install applications the easiest way is via helm.

    As you can see the setup of a kubernetes cluster in one of the major hyperscalers is very easy. A few lines of code and you’re up and running. Add those lines into a shell script and standing up clusters can be a single command…just don’t forget to tear it down when you’re done!

  • Streamline Kubernetes Management through Automation

    Automation in managing Kubernetes clusters has burgeoned into an essential practice that enhances efficiency, security, and the seamless deployment of applications. With the exponential growth in containerized applications, automation has facilitated streamlined operations, reducing the room for human error while significantly saving time. Let’s delve deeper into the crucial role automation plays in managing Kubernetes clusters.

    Section 1: The Imperative of Automation in Kubernetes

    1.1 The Kubernetes Landscape

    Before delving into the nuances of automation, let’s briefly recapitulate the fundamental components of Kubernetes, encompassing pods, nodes, and clusters, and their symbiotic relationships facilitating a harmonious operational environment.

    1.2 The Need for Automation

    Automation emerges as a vanguard in managing complex environments effortlessly, fostering efficiency, reducing downtime, and ensuring the optimal utilization of resources.

    1.2.1 Efficiency and Scalability

    Automation in Kubernetes ensures that clusters can dynamically scale based on the workload, fostering efficiency, and resource optimization.

    1.2.2 Reduced Human Error

    Automating repetitive tasks curtails the scope of human error, facilitating seamless operations and mitigating security risks.

    1.2.3 Cost Optimization

    Through efficient resource management, automation aids in cost reduction by optimizing resource allocation dynamically.

    Section 2: Automation Tools and Processes

    2.1 CI/CD Pipelines

    Continuous Integration and Continuous Deployment (CI/CD) pipelines are at the helm of automation, fostering swift and efficient deployment cycles.

    pipeline:
      build:
        image: node:14
        commands:
          - npm install
          - npm test
      deploy:
        image: google/cloud-sdk
        commands:
          - gcloud container clusters get-credentials cluster-name --zone us-central1-a
          - kubectl apply -f k8s/
    

    Code snippet 1: A simple CI/CD pipeline example.

    2.2 Infrastructure as Code (IaC)

    IaC facilitates the programmable infrastructure, rendering a platform where systems and devices can be managed through code.

    apiVersion: v1
    kind: Pod
    metadata:
      name: mypod
    spec:
      containers:
      - name: mycontainer
        image: nginx
    

    Code snippet 2: Defining a Kubernetes pod using IaC.

    2.3 Configuration Management

    Tools like Ansible and Chef aid in configuration management, ensuring system uniformity and adherence to policies.

    - hosts: kubernetes_nodes
      tasks:
        - name: Ensure Kubelet is installed
          apt: 
            name: kubelet
            state: present
    

    Code snippet 3: Using Ansible for configuration management.

    Section 3: Automation Use Cases in Kubernetes

    3.1 Auto-scaling

    Auto-scaling facilitates automatic adjustments to the system’s computational resources, optimizing performance and curtailing costs.

    3.1.1 Horizontal Pod Autoscaler

    Kubernetes’ Horizontal Pod Autoscaler automatically adjusts the number of pod replicas in a replication controller, deployment, or replica set based on observed CPU utilization.

    apiVersion: autoscaling/v2beta2
    kind: HorizontalPodAutoscaler
    metadata:
      name: myapp-hpa
    spec:
      scaleTargetRef:
        apiVersion: apps/v1
        kind: Deployment
        name: myapp
      minReplicas: 1
      maxReplicas: 10
      metrics:
      - type: Resource
        resource:
          name: cpu
          target:
            type: Utilization
            averageUtilization: 50
    

    Code snippet 4: Defining a Horizontal Pod Autoscaler in Kubernetes.

    3.2 Automated Rollouts and Rollbacks

    Kubernetes aids in automated rollouts and rollbacks, ensuring application uptime and facilitating seamless updates and reversions.

    3.2.1 Deployment Strategies

    Deployment strategies such as blue-green and canary releases can be automated in Kubernetes, facilitating controlled and safe deployments.

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: myapp
    spec:
      strategy:
        type: RollingUpdate
        rollingUpdate:
          maxSurge: 25%
          maxUnavailable: 25%
      selector:
        matchLabels:
          app: myapp
      template:
        metadata:
          labels:
            app: myapp
        spec:
          containers:
          - name: myapp
            image: myapp:v2
    

    Code snippet 5: Configuring a rolling update strategy in a Kubernetes deployment.

    Conclusion: The Future of Kubernetes with Automation

    As Kubernetes continues to be the frontrunner in orchestrating containerized applications, the automation integral to its ecosystem fosters efficiency, security, and scalability. Through a plethora of tools and evolving best practices, automation stands central in leveraging Kubernetes to its fullest potential, orchestrating seamless operations, and steering towards an era of self-healing systems and zero-downtime deployments.

    In conclusion, the ever-evolving landscape of Kubernetes managed through automation guarantees a future where complex deployments are handled with increased efficiency and reduced manual intervention. Leveraging automation tools and practices ensures that Kubernetes clusters not only meet the current requirements but are also future-ready, paving the way for a robust, scalable, and secure operational environment.


    References:

    1. Kubernetes Official Documentation. Retrieved from https://kubernetes.io/docs/
    2. Jenkins, CI/CD, and Kubernetes: Integrating CI/CD with Kubernetes (2021). Retrieved from https://www.jenkins.io/doc/book/
    3. Infrastructure as Code (IaC) Explained (2021).
    4. Understanding Kubernetes Operators (2021).
  • 90 days to success in DevOps

    Starting a new role? Maybe this is the first foray into DevOps or Platform Engineering? What is needed to “hit the ground running” in a new role? Leaders in high positions of a company typically have a “100 day rule” to prove themselves. Let’s round it out with 3 months of progress for success.

    In most enterprises on boarding new talent is typically left to the new employee. This is very unfortunate because the first 90 days of a new role will impact not only the new employee, but their immersion into the culture and their view of the company. Bottom line, in most cases it is up to the new employee to “learn the ropes” in navigating their new position.

    The first 30 days

    This month is usually the most important for everyone. The first thing a new employee needs to do is find a good mentor especially if they are not assigned one. Seek out those with institutional knowledge who knows how to navigate the company politics. Find someone who knows how the systems work, how to gain the access needed to be successful in the role. The mentor would have knowledge of “how things work” and what is seen as best practice for accomplishing the tasks at hand.

    Some things to know:

    • Who’s who in the organization? – an org chart
    • How mature are they as a development organization?
    • What are the processes to put code into production?
    • Are the processes manual or automated?
    • What is the expectation of you on a day to day basis?

    There is plenty more to uncover, but this will help to get started. Once the processes are understood and access is granted to perform the role, find some quick wins. Listen closely to where the frustrations may lie within your organization. Maybe the previous employee in this role didn’t automate certain tasks…submit a small PR to help.

    It’s important to find some quick wins for many reasons. First it helps “break the ice”. It also shows strengths. Maybe there’s a way to improve some docs. There may be some ideas brought in from previous experience to help with a particular pain point.

    The first 30 days is important to uncover the expectations of the team. Talking to stakeholders and “the customer” is important to get a big picture of what works and what doesn’t in order to find quick wins to make an impact early.

    Days 30-60

    The first 4 weeks are usually greeted with firehose sessions daily. Take a bit to digest everything. Review notes, brainstorm ideas, understand how the team and the company works. Armed with the broader knowledge about the organization, the team, and how things work at a high level it’s time to dig deeper into where the biggest impacts can be achieved.

    In this 30 day block uncover:

    • The maturity of the team?
    • What is the approval process for delivering code to production?
    • What steps are needed to approve PRs?
    • How does code flow through the various systems?
    • What amount of QA is performed?

    Find ways to help the team be more efficient. Listen to the complaints and see where possible improvements could be made. Again, quick wins are key at this stage. As a fresh face, a lot of times gaining access to otherwise inaccessible groups within the organization is usually fairly easy. Keep an ear to the ground to find ways to create impactful suggestions

    It is important to remember as people get to know a new employee the interactions have lasting impacts. Ensure there is adequate listening and relevant questions to get underneath a complaint. Avoid making off hand suggestions, but rather find some common issues. Start to tackle the common issues and socialize improvements. The key here to to avoid “calling the baby ugly”.

    Days 60-90

    This is where a new employee’s impact can accelerate. At this stage having the access needed to be successful would be complete. Hopefully there’s been a few quick wins, new co-workers are impressed, and there’s been positive impact on the team.

    Regular interaction with your leader would have been established. A solid understanding of what is expected is created and the mentor has made an impact. Knowing where to go to get answers if there is a roadblock and knowing how to avoid the “potholes in the road” is key.

    This stage is where the “rubber hits the road”. Gaining traction in the day to day and making regular impact to the business is routine at this point. This is where all of the knowledge gained in the first 60 days can be parlayed into a winning hand.

    What success looks like

    The first 3 months of any new position sets the stage for every new employee. Creating a positive impression on the team helps build credibility within the broader organization and is key to instilling the confidence needed to being successful overall.

    It may take far more than 90 days to feel comfortable with the role and that is okay. As long as there is a consistent method for learning and mistakes are not repeated the impact new employees make is usually sustainable for a long time. Make the best of it and keep track of the wins and losses for the inevitable review with “the boss”.

    You got this. Go.

  • What’s missing in Kubernetes

    Kubernetes is an open-source container orchestration system that automates the deployment, scaling, and management of containerized applications. It is widely used for its ability to manage containers at scale and is the de facto standard for container orchestration. However, despite its broad adoption, there are still a few missing pieces that need to be addressed to make it fully functional.

    Network Setup

    One of the main missing pieces in Kubernetes is a proper network setup. Kubernetes allows for the creation of multiple clusters, each with its own set of nodes, but it requires a well-defined network setup to manage communication between these clusters.

    Without proper network setup, nodes in the same cluster may not be able to communicate with each other, or there may be issues with cross-cluster communication. This can result in application downtime, loss of data, and other issues that can impact business operations.

    One solution to this problem is to use a software-defined networking (SDN) approach that allows for the creation of a virtual network infrastructure. An SDN controller can be used to manage the virtual network infrastructure and provide network services such as load balancing, routing, and security. With SDN, Kubernetes clusters can be properly connected, and communication between clusters can be streamlined.

    Security

    Another missing piece in Kubernetes is security. Kubernetes provides some basic security features such as role-based access control (RBAC) and network policies, but these are not always enough to secure the entire system.

    Security is a critical aspect of any container orchestration system, and Kubernetes is no exception. Kubernetes clusters are complex systems with many components, and securing them requires a multi-layered approach.

    To enhance security, Kubernetes clusters should be set up with secure communication channels and encrypted data storage. Additionally, it is important to create and enforce security policies that prevent unauthorized access to the system. This includes implementing identity and access management (IAM) policies, network segmentation, and regular vulnerability scanning.

    Monitoring and Logging

    Kubernetes also lacks inbuilt monitoring and logging capabilities. While Kubernetes includes some basic monitoring features, such as health checks and resource usage metrics, it does not provide comprehensive monitoring and logging capabilities.

    In a production environment, it is essential to have comprehensive monitoring and logging capabilities to ensure the health and availability of the system. Kubernetes clusters should be set up with a logging and monitoring stack that can collect and analyze logs and metrics from all nodes in the cluster. This can provide insights into the health and performance of the system, as well as help identify and troubleshoot issues.

    Conclusion

    Kubernetes is a powerful container orchestration system, but there are still a few missing pieces that need to be addressed to make it fully functional. A well-defined network setup, enhanced security, and proper monitoring and logging are all essential components of a fully functional Kubernetes environment.

    With the increasing adoption of containers and cloud-native applications, Kubernetes is becoming more important than ever. As organizations continue to adopt Kubernetes, it is important to ensure that the missing pieces are addressed to provide a reliable and scalable platform for containerized applications. By addressing these missing pieces, Kubernetes can continue to evolve and improve, providing a robust and secure platform for developers and IT teams.

  • Running OpenAI in Kubernetes

    Using the OpenAI API with Python is a powerful way to incorporate state-of-the-art natural language processing capabilities into your applications. This blog post provides a step-by-step walk through for creating an OpenAPI account, obtaining an API key, and creating a program to perform queries using the OpenAI API. Additionally, an example demonstrating how to create a podman image to run the code on Kubernetes is provided.

    Creating an OpenAI Account and API Key

    Before building the code, create an OpenAI account and obtain an API key. Follow these steps:

    1. Go to the OpenAI website.
    2. Click on the “Sign up for free” button in the top right corner of the page.
    3. Fill out the registration form and click “Create Account”.
    4. Once an account has been created, go to the OpenAI API page.
    5. Click on the “Get API Key” button.
    6. Follow the prompts to obtain a API key.

    Installing Required Packages

    To use the OpenAI API with Python, install the OpenAI package. Open a command prompt or terminal and run the following command:

    pip install openai

    Using the OpenAI API with Python

    With the OpenAI account and API key, as well as the required packages installed, write a simple Python program. In this example, create a program that generates a list of 10 potential article titles based on a given prompt.

    First, let’s import the OpenAI package and set our API key:

    import openai
    openai.api_key = "YOUR_API_KEY_HERE"

    Next, define the prompt:

    prompt = "10 potential article titles based on a given prompt"

    Now use the OpenAI API to generate the list of article titles:

    response = openai.Completion.create(
        engine="text-davinci-002",
        prompt=prompt,
        max_tokens=50,
        n=10,
        stop=None,
        temperature=0.5,
    )
    titles = [choice.text for choice in response.choices]
    

    Let’s break this down:

    • engine="text-davinci-002" specifies which OpenAI model to use. This example uses the “Davinci” model, which is the most capable and general-purpose model currently available.
    • prompt=prompt sets the prompt to our defined variable.
    • max_tokens=50 limits the number of tokens (words) in each generated title to 50.
    • n=10 specifies that we want to generate 10 potential article titles.
    • stop=None specifies that we don’t want to include any stop sequences that would cause the generated text to end prematurely.
    • temperature=0.5 controls the randomness of the generated text. A lower temperature will result in more conservative and predictable output, while a higher temperature will result in more diverse and surprising output.

    The response variable contains the API response, which includes a list of choices. Each choice represents a generated title. This will extract the generated titles from the choices list and store them in a separate titles list.

    Finally, print out the generated titles:

    for i, title in enumerate(titles):
        print(f"{i+1}. {title}")

    This will output something like:

    1. 10 Potential Article Titles Based on a Given Prompt
    2. The Top 10 Articles You Should Read Based on This Prompt
    3. How to Come Up with 10 Potential Article Titles in Minutes
    4. The Ultimate List of 10 Article Titles Based on Any Prompt
    5. 10 Articles That Will Change Your Perspective on This Topic
    6. How to Use This Prompt to Write 10 Articles Your Audience Will Love
    7. 10 Headlines That Will Instantly Hook Your Readers
    8. The 10 Most Compelling Article Titles You Can Write Based on This Prompt
    9. 10 Article Titles That Will Make You Stand Out from the Crowd
    10. The 10 Best Article Titles You Can Write Based on This Prompt

    And that’s it! You’ve successfully used the OpenAI API to generate a list of potential article titles based on a given prompt.

    Creating a Podman Image to Run on Kubernetes

    To run the program on Kubernetes, create a podman image containing the necessary dependencies and the Python program. Here are the steps to create the image:

    1. Create a new file called Dockerfile in a working directory.
    2. Add the following code to the Dockerfile:
    FROM python:3.8-slim-buster
    RUN pip install openai
    WORKDIR /app
    COPY your_program.py .
    CMD ["python", "your_program.py"]

    This file tells Docker to use the official Python 3.8 image as the base, install the openai package, set the working directory to /app, copy your Python program into the container, and run the program when the container starts.

    To build the image:

    1. Open a terminal or command prompt and navigate to a working directory.
    2. Build the image by running the following command:
    podman build -t your_image_name . 

    Replace “image_name” with the name for the image.

    To run the image:

    podman run image_name

    This will start a new container using the image created and subsequently run the program created above.

    Verify the image runs and spits out what the desired output. Run it on a Kubernetes cluster as a simple pod. There are two ways to accomplish this in Kubernetes, declaratively or imperatively.

    Imperative

    The imperative way is quite simple:

    kubectl run my-pod --image=my-image

    This command will create a pod with the name “my-pod" and the image “my-image".

    Declarative

    The declarative way of creating a Kubernetes pod involves creating a YAML file that describes the desired state of the pod and using the kubectl apply command to apply the configuration to the cluster.

    apiVersion: v1
    kind: Pod
    metadata:
      name: my-pod
    spec:
      containers:
        - name: my-container
          image: my-image
    

    Save it as “my-pod.yaml”

    Outside of automation running this on the Kubernetes cluster from the command line can be accomplished with:

    kubectl apply -f my-pod.yaml

    This command will create a pod with the name “my-pod" and the image “my-image". The -f option specifies the path to the YAML file containing the pod configuration.

    Obviously this is quite simple and there’s plenty of ways to accomplish running this code in Kubernetes as a deployment or replicaset or some other method.

    Congratulations! Using the OpenAI API with Python and creating a podman image to run a program on Kubernetes is quite straightforward. With these tools available. Incorporating the power of natural language processing into your applications is both straightforward and very powerful.