Skip to content

kubernetesdaily/kubers-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

kubers-demo

Introduction kubers

Install Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustc --version
rustc 1.68.0-nightly (b70baa4f9 2022-12-14)

Install Minikube
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-darwin-amd64
sudo install minikube-darwin-amd64 /usr/local/bin/minikube
minikube start 
kubectl get ns 
NAME              STATUS   AGE
default           Active   15s
kube-node-lease   Active   15s
kube-public       Active   15s
kube-system       Active   15s

initialize rust binary using cargo package manager

cargo init 

update cargo.toml dependencies

[package]
name = "kubers-demo"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
kube = { version = "0.87.2", features = ["client","runtime", "derive", "rustls-tls"] }
k8s-openapi = { version = "0.20.0", features = ["latest"] }
tokio = { version = "1.0", features = ["full"] }  # Use the latest version
[dev-dependencies]
k8s-openapi = { version = "0.20.0", features = ["latest"] }
async-std = "1.0"  # Use the latest version


update main.rs
use kube::{Client, Api};
use kube::api::ListParams;
use k8s_openapi::api::core::v1::Pod;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Load the kubeconfig file.
    let config = kube::Config::from_kubeconfig(&kube::config::KubeConfigOptions::default()).await?;
    let client = Client::try_from(config)?;

    // Work with Kubernetes API.
    let pods: Api<Pod> = Api::default_namespaced(client);
    let lp = ListParams::default();

    for p in pods.list(&lp).await? {
        println!("Found Pod: {}", p.metadata.name.unwrap_or_default());
    }

    Ok(())
}



deploy simple ngnix deployment

kubectl apply -f https://k8s.io/examples/application/deployment.yaml

Cargo build

cargo build

Cargo Run

cargo run

run rust code to talk with kubectl and get upate to using rust kube crate

cargo run -- --kubers-demo kubectl -- get po

build own CRD with meetup example

cargo init kube-crd 

update your main.rs

use kube::{Api, Client};
use kube::api::PostParams;
use serde::{Serialize, Deserialize};
use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::{
    CustomResourceDefinition,
    CustomResourceDefinitionSpec,
    CustomResourceDefinitionNames,
    CustomResourceDefinitionVersion,
    JSONSchemaProps,
    CustomResourceValidation,
    JSONSchemaPropsOrArray,
};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
use schemars::JsonSchema;
use kube::CustomResource;
use std::collections::BTreeMap;

// Define the spec of our custom resource
#[derive(CustomResource, Deserialize, Serialize, Clone, Debug, JsonSchema)]
#[kube(group = "example.com", version = "v1", kind = "KCDTrack2", namespaced)]
pub struct MeetupSpec {
    organizer: String,
    topic: String,
    attendees: Vec<String>,
    conference: String,
    time: String,
    session_type: String,
    speaker: String,
}

// Main function to create the CRD in the cluster
#[tokio::main]
async fn main() -> Result<(), kube::Error> {
    let client = Client::try_default().await?;

    let crds: Api<CustomResourceDefinition> = Api::all(client);
    let pp = PostParams::default();

    // Define the CRD for our KCDTrack2 resource
    let kcd_crd = CustomResourceDefinition {
        metadata: ObjectMeta {
            name: Some("kcdtrack2s.example.com".to_string()),
            ..Default::default()
        },
        spec: CustomResourceDefinitionSpec {
            group: "example.com".to_string(),
            versions: vec![
                CustomResourceDefinitionVersion {
                    name: "v1".to_string(),
                    served: true,
                    storage: true,
                    schema: Some(CustomResourceValidation {
                        open_api_v3_schema: Some(JSONSchemaProps {
                            type_: Some("object".to_string()),
                            properties: Some({
                                let mut props = BTreeMap::new();
                                props.insert("spec".to_string(), JSONSchemaProps {
                                    type_: Some("object".to_string()),
                                    properties: Some({
                                        let mut spec_props = BTreeMap::new();
                                        spec_props.insert("organizer".to_string(), JSONSchemaProps {
                                            type_: Some("string".to_string()),
                                            ..Default::default()
                                        });
                                        spec_props.insert("topic".to_string(), JSONSchemaProps {
                                            type_: Some("string".to_string()),
                                            ..Default::default()
                                        });
                                        spec_props.insert("attendees".to_string(), JSONSchemaProps {
                                            type_: Some("array".to_string()),
                                            items: Some(JSONSchemaPropsOrArray::Schema(Box::new(JSONSchemaProps {
                                                type_: Some("string".to_string()),
                                                ..Default::default()
                                            }))),
                                            ..Default::default()
                                        });
                                        spec_props.insert("conference".to_string(), JSONSchemaProps {
                                            type_: Some("string".to_string()),
                                            ..Default::default()
                                        });
                                        spec_props.insert("time".to_string(), JSONSchemaProps {
                                            type_: Some("string".to_string()),
                                            ..Default::default()
                                        });
                                        spec_props.insert("session_type".to_string(), JSONSchemaProps {
                                            type_: Some("string".to_string()),
                                            ..Default::default()
                                        });
                                        spec_props.insert("speaker".to_string(), JSONSchemaProps {
                                            type_: Some("string".to_string()),
                                            ..Default::default()
                                        });
                                        spec_props
                                    }),
                                    ..Default::default()
                                });
                                props
                            }),
                            ..Default::default()
                        }),
                    }),
                    ..Default::default()
                }
            ],
            names: CustomResourceDefinitionNames {
                plural: "kcdtrack2s".to_string(),
                singular: Some("kcdtrack2".to_string()),
                kind: "KCDTrack2".to_string(),
                short_names: Some(vec!["kcdt2".to_string()]),
                ..Default::default()
            },
            scope: "Namespaced".to_string(),
            ..Default::default()
        },
        status: None,
    };

    // Create the CRD
    crds.create(&pp, &kcd_crd).await?;

    Ok(())
}

build you code

cargo build 

deploy simple kubernetes app


 kubectl apply -f https://k8s.io/examples/application/deployment.yaml

Cargo run

cargo run -- --kubers-demo kubectl -- get po    

get the CRD

kubectl get crd  

deploy own CRD via YAML

apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: keynote-live-streaming
spec:
  organizer: "kcdhyd"
  topic: "Keynotes Live Streaming"
  attendees: []
  conference: "KCD Hyderabad"
  time: "09:30"
  session_type: "Keynote"
  speaker: ""

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: supply-chain-security-2024
spec:
  organizer: "kcdhyd"
  topic: "Supply Chain Security in 2024"
  attendees: []
  conference: "KCD Hyderabad"
  time: "11:20 - 11:40"
  session_type: "Expert Keynote"
  speaker: "Saiyam Pathak, Founder KubeSimplify"

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: role-of-ebpf
spec:
  organizer: "kcdhyd"
  topic: "The Role of eBPF in Kubernetes Networking and Security"
  attendees: []
  conference: "KCD Hyderabad"
  time: "11:40 - 12:05"
  session_type: "Session"
  speaker: "Rajani Ekunde, GlobalLogic; Kunal Sarpalti, Scrobits Technologies LLP"

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: ecs-to-eks
spec:
  organizer: "kcdhyd"
  topic: "How migrating from ECS to EKS supercharged our infrastructure"
  attendees: []
  conference: "KCD Hyderabad"
  time: "12:05 - 12:15"
  session_type: "Lightning Talk"
  speaker: "Harsh Singh, Indmoney"

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: managing-kubernetes
spec:
  organizer: "kcdhyd"
  topic: "Beyond Connectivity: Managing Kubernetes in Air-Gapped Environments"
  attendees: []
  conference: "KCD Hyderabad"
  time: "12:15 - 12:40"
  session_type: "Session"
  speaker: "Unnati Mishra, VMware; Akshat Khanna, Astuto"

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: security-conscious-cicd
spec:
  organizer: "kcdhyd"
  topic: "Introduction to security-conscious CI/CD pipeline"
  attendees: []
  conference: "KCD Hyderabad"
  time: "12:40 - 12:50"
  session_type: "Lightning Talk"
  speaker: "Shyam Mohan Kanojia, RazorOps"

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: open-source-community
spec:
  organizer: "kcdhyd"
  topic: "Developing Open Source Community in Hyderabad"
  attendees: []
  conference: "KCD Hyderabad"
  time: "14:00 - 14:25"
  session_type: "Panel Discussion"
  speaker: "Amogha, Kalyan, Vineeth, Zubair"

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: intro-to-grafana-loki
spec:
  organizer: "kcdhyd"
  topic: "Introduction to Grafana Loki"
  attendees: []
  conference: "KCD Hyderabad"
  time: "14:25 - 14:50"
  session_type: "Session"
  speaker: "Ashwanth Goli, Grafana"

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: hyperledger-fabric
spec:
  organizer: "kcdhyd"
  topic: "Falcon Flight: Effortless Deployment of Hyperledger Fabric in Kubernetes"
  attendees: []
  conference: "KCD Hyderabad"
  time: "14:50 - 15:15"
  session_type: "Session"
  speaker: "Sanchit Johari, NPCI; Arpan Aldakhiya, NPCI"

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: kyverno-talk
spec:
  organizer: "kcdhyd"
  topic: "Let's Talk Kyverno"
  attendees: []
  conference: "KCD Hyderabad"
  time: "15:45 - 15:55"
  session_type: "Lightning Talk"
  speaker: "Toshat Khawale, JP Morgan Chase"

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: integrating-rust
spec:
  organizer: "kcdhyd"
  topic: "Building the Bridge: Integrating Rust with Kubernetes Controller Runtime"
  attendees: []
  conference: "KCD Hyderabad"
  time: "15:55 - 16:20"
  session_type: "Session"
  speaker: "Sangam Biradar, CloudNativeFolks"

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: wasm-deployment
spec:
  organizer: "kcdhyd"
  topic: "Streamlining Wasm Deployment in Kubernetes with SpinKube"
  attendees: []
  conference: "KCD Hyderabad"
  time: "16:20 - 16:45"
  session_type: "Session"
  speaker: "Tamil Vanan, Arcesium"

---
apiVersion: example.com/v1
kind: KCDTrack2
metadata:
  name: kubechecks
spec:
  organizer: "kcdhyd"
  topic: "kubechecks - Fearless Kubernetes App Updates"
  attendees: []
  conference: "KCD Hyderabad"
  time: "16:45 - 16:55"
  session_type: "Lightning Talk"
  speaker: "Ratnadeep Debnath, Zapier"

kubectl apply -f kcdhyd.yaml  
kubectl get kcdtrack2

kubectl get kcdtrack2 integrating-rust   -o jsonpath='{.spec.speaker}'

Lets play around kube-open-api

cargo init kube-rs-slack

update main.rs file wih following

use kube::{Client, Api};
use kube::runtime::watcher;
use k8s_openapi::api::core::v1::Pod;
use tokio;
use reqwest;
use serde_json::json;
use futures_util::TryStreamExt;

async fn send_slack_message(webhook_url: &str, message: &str) {
    let client = reqwest::Client::new();
    if let Err(e) = client.post(webhook_url)
        .json(&json!({ "text": message }))
        .send()
        .await {
        eprintln!("Failed to send message to Slack: {}", e);
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::try_default().await?;
    let pods: Api<Pod> = Api::all(client.clone());

    let watcher = watcher(pods, Default::default());

    let slack_webhook_url = "******"; // Replace with your Slack webhook URL

    tokio::pin!(watcher);
    while let Some(event) = watcher.try_next().await? {
        if let watcher::Event::Applied(pod) = event {
            let pod_name = pod.metadata.name.unwrap_or_default();  
            let message = format!("Pod update: {}", pod_name);
            send_slack_message(slack_webhook_url, &message).await;
        }
    }

    Ok(())
}


create custom app and set channel where you get messages

lets run the binary cargo run

open another terminal do any deployements you get updates in channel

Releases

No releases published

Packages

No packages published

Languages