Wednesday, May 12, 2021

Kubernetes - constraint security

security constraint

constraint the security/process with limited previledge

limited power

UID ==0
UID >= 1000

SElinux

container Security

SEC Constraint

- Run the process with limited power.

login to your system with normal user say sam
$ cat /etc/shadow
access denied

try with root,
# cat /etc/shadow

Create a deploymnet
kc createdeploy myd --image--vimal13/apache-webserver-phop
> kc get pods
> kc get pod
> kc exec -it myd-xxxx -- sh

# id
# ps -aux

you are runnig as a root user

# sleep 20 &
# ps -aux
you see sleep is running as a root.

> kc describe pods mypod....

kc get pods myd-xx -o yaml > p.txt
> noteapd p.txt

go see review it, you will see security context and there is nothing

securityContext: {}

how can you constrain with limited power?


more security-context

spec:
  securityContext:
    runAsUser: 1000
    runAsUser: 3000
    fsGroup: 2000
  containers:
  - name: sec-ctx-demo
    image: busybox
    commaand: [ "sh", "-c", "sleep 1h" ]
    volumeMounts:
...

> kc apply -f security-context.yaml
> kc get pods
> kc exec -it security-context-demo -- sh
$ id
you see id of 1000 and gid=3000
$ ps




# vi t.py
import time
time.sleep(300)
# python3 t.py
it started

open a new terminal
# ps -aux | grep t.py



Cap -> capibility
when process start, what is its capability?
- change network setting?
- change network stack?
- change time?

whats the capability of the process.

You can write your process on some language, and run with proper capability.

$ date
$ date 1212121212

you get error, not permitted
you don't have capability to change the time as normal user

$ ifconfig
$ ifconfig eth0 1.2.3.4
operation not permitted


# cat security-context_cap.yaml

spec:
  containers:
  - name: sec-ctx-4
    imageL gcr.io/google-samples/node-hello:1.0
    securityContext:
      capabilities:
        add ["Net_Admin..


> kc apply -f security-context_cap.yaml
> kc exec -it security-context-demo-4 -- sh

# ps -auz


[12:24]

# ifconfig
# ip a s
# ip addr add 1.2.3.4/24 dev eth0
# ip a s

This is a concept of constraint.


Limits and quotas

> kc delete all --all


user (image)  --> master

node1 - 4GB/4CPU
node2 - 16GB/6CPU
node3 - 16GB/16cpu

when you launch a new container, you have min requirement 1 GB RAM/2 cpu
kube scheduler checks on node and find which node has RAM, CPU available based on requirement.
if ram is availablem, it will launch on that available node, if that much RAM/CPU not available container will be on pending state.

Limit request

you defined minimum requirement, but not the maximum requirement.

[heap memory]

it is always a good practice to set a max limit.
when pod launch, there are lots of process running and it may use more resources, so its a good idea to limit the max value.

> kc create deploy

> kc get pods myd-... -o yaml > z.txt
> notepad z.txt
review all the output

go down, look for limit


missed about 5 minutes here,

> kc get limitrange
> kc describe limitrange
>


notepad limitrange_pod.yaml


limit range is per name space

> kc get pods



Quota

Namespace

create a user with RBAC
- constraint this user with particular namespace.

- Create ns
- create ns
- set rbac to this user, power to work on this particular ns

There is no constarint and they have full control for
pvc, pc, rc, svc ....
create n number of pods

what we do?
we can tell our ns, max pv, pvc or anything set limit
say pod=3, pvc=2 - limit the resource

This information can be done with quotas.

> kc get quota

> kc create namespace lw1
> lc get quota --namespace lw1
no resource found...

quota

spec:
  hard:
    requests.cpu: "1"
    requests.memory: 1Gi
    limits.cpu: "2"
    limits.mem......

> kc apply -f quotas.yaml --namespace lw1

you can create quota from command line too

> kc create --help
look for example
> kc create quota myq --hard=cpu=1,memory=1G, pods=2,services=3,replicatoncontroller=2,resourcequotas=1,secrets=5,persistentvolumeclaims=10

> kc get pvc
> kc get quota
> kc get pods

metric Server
-------------

its very important to monitor your servers.
its hard to see what is going on for admin.
on k8s, if pod fails, it will re launch.

how many ram/CPU using/free , whats the free resources available, this is also called metrics.

used to be a tool called heapster - but now, its a metrics server (download from github)

install, and run.
this pod runs as an agent. They install cagent. (runs as daemon sets)

> minikube addon enable metrics-server

> kc top pod

it can monitor node or pod


> kc top node
shows you use %

This tool does not give you detail but you can integrate, cloud metric agent.
or you can use
splunx
new ..
prometheus/grafana









Day 40 - AWS - Elastic Container Service (ECS cluster)

AWS - Session 40 Apr 23, 2021

Elastic Container Service (ECS cluster)

1. Start your local RHEL8 machine

App -> OS (App/web server) -> Create image (AMI) -> launch on platform

Image -> AMI -> EC2

cpu/Ram
Hypervisor(Xen)
VM1 VM2 (Shared Resources)

or launch OS on dedicated host

containerization

Image -> Containers

Basic inf about Docker
---------------------

# docker info
# docker images

docker hun

# docker run -dit --name z1 vimal12/apache-webserver-php

# docker inspect z1

reviw the ip
# docker ps
# curl 182.17.0.2/index.php

if you want to connect from outside, it does not work

You have to expose

# docker run -dit --name z2 -p 8080:80 vimal13/apache-webserver-php

-p mean patting

# docker ps

# ifconfig enp0s3
get the IP

what we mean on above docker run command is that any request comes to <hostIP>:8080 is redirected to docker_ip:80

so, lets try this at your browser
http://192.168.10.20:8080

# docker run -dit --name z3 -p 8081:80 vimal13/apache-webserver-php
Every time you launch a new instance, you have to change the port number otherwise it will fail.

# netstat -tnlp | grep 8080

two program can't run on one single port

# docker run -dit --name z4 -p 8082 vimal13/apache-webserver-php

rather than specifying port number to every instance, docker folk came up with idea to assign the port automatically.

# docker run -dit --name z5 -P vimal13/apache-webserver.php

-P (Upper case) - publish
it will take random port and expose it.

# docker ps
# docker run -dit --name z6 -P vimal13/apache-webserver.php
# docker ps

# docker run -dit --name z2 -P vimal13/apache-webserver-php

Lets talk about ECS


we have
HW
- SYSTEM - RHEL8 -> Docker Engine -> Containers

AWS will provide the HW (System)

EC2 will provide RAM/CPU

Women glow differently when they are treated right and loved properly.

Monday, May 10, 2021

Day1- Introduction to Terraform

 ðŸ‘‰ Why Terraform is used for?
- Terraform is an infrastructure provisioning tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions. It is used to manage infrascture using HashiCorp Configuration Language (HCL) code (also known as IAC or Infrastructure as Code) to automate the provision of the infrastructure. It uses a very simple syntaxt and can be provision the infracture across multiple cloud and on-premises data centers. We can safely and efficiently provision/reprovision the infrascture (at VMWare, AWS, GCP, and deploys infrastructure) for any configuration changes. It is one of the most popular tool available as IAC - infrascture as Code.
Configuration files describe to Terraform the components needed to run a single application or your entire datacenter.


👉 What is Infrastructure as Code ?
- Infrascture as code means defining infracture in a code which when executed, it creates or builds or provisions infrascture (Servers, routers and more) based on the written code. or you can say, IAC is a method of managing and provisioning the computer systems in data center using machine readable definition files, rather than physical hardware configuration or interactive configuration tools.

Infrastructure as code (IaC) means to manage your IT infrastructure using configuration files.

IaC helps to aotomate the provision of infrascture, allow your organization to develop, deploy, and scale  your cloud applications with reduced cost and faster and risk free fashion.

👉 What's the difference between Terraform and ansible?
- Terraform is infrascture management tool which ansible is mostly use for configuration management. They can do both jobs but there are little differences between them.
- Terraform is opensource , declarative tool which ansible is both declarative and procedural configuration.

👉 What is provider in Terraform?
- Provider is the keyword used in terraform which specifiy you what cloud environment you will be working on. The value you define for provider will decide where you rinfrascture will be provisioned. Based on the provider, the plugins are downloaded which will interact with remove system. You must declare the provider while writing the code.

The providers (AWS, AZURE, GCP and etc) are used to provision a resources.


Thursday, May 6, 2021

day 3 - Terraform - data reference - data manupulation

 Day3 - Terraform  5-06-2021

data reference/data manupulation

data resource in terrraform
In programming language, you define value and print
x=5
y="Hi"

print(x)
print(y)

resource is very important. EC2 is one of the resource. Please visit terraform doc for cloud specific resources such as aws ec2.


how to define variable in terraform?

You write in block with keywork. yesterday we use keyword as resource. lets try today with variable.


variable "x" {
  type = string    # value of string is string
  default = "Terraform Training"    # define the default value.
}

# keywork

keywork "name" {
}

here we will use keywork as output

output "myvalue" {
  value = x
}

lets put together
$ cat ec2.tf
variable "x" {
  type = string    # value of string is string
  default = "Terraform Training"    # define the default value.
}

output "myvalue" {
  value = x
}


lets go for an example

> terraform apply

we got an error: Invalie reference

what this mean is 'what you are typing, i have no idea


lets modify and return

  value = "x"    # put in double quote

terraform apply

type yes when prompted

you see outpyt myvalue=x
x is printed as it is.

you have to define x as a variable

so
value  "var.x"

run it again,

we see myvalue = "var.x"

if you put inside double quote, it will print as it is.

x is a reference, need to look for value, so we have to use curly braces.

value = "${var.x}"

$ cat ec2.tf
variable "x" {
  type = string    # value of string is string
  default = "Terraform Training"    # define the default value.
}

output "myvalue" {
  value = "${var.x}"
}

run it again

lets modifey

value = "Hi ${var.x} its cool"

this is called string interpolation


if you want to print any variable, you have to define where is it defined.
you have to specify the keywork - var.

variable you created are user defined variable and var variable will look for the data that is defined to x.

------------------------------

whats the plan

launch os : name of the service ec2
     sub service instance
in terraform we call instance as resource.

lets see we want to attach a disk to the instance, we can get extra storage from aws, the service name is ebs.

ebs -> volume -> storage -> hard disk (block device)

ebs is sub service to ec2.

in AWS, you create instance at a region

lets go to ec2 -> ebs -> volume
when we create volume
- it will ask the size of the volume
- it will ask you availibity zone where you want to deploy.

1. launch OS - ec2
2. Create a volume (dish)
3. Attach volume to ec2.

The biggest problem is that you need to create harddisk at the same region where you have created ec2 instance.

-> when you launch os, it automatically assign what az (by default), it will launch.


> mkdir ec2; cd ec2
lets reference yesterday's code


> notepad terraform.tf
provider "aws" {

region = "ap-south-1"
access_key = ""
secret_key = ""

}

resource "ec2 instance" "os1" {    # os1 is resource name

ami ="ami-01938d8s003ds88ss"
instance_type = "t2.small"
tags = {
  Name = "My first OS New"
    }
}
> terraform apply


------------------
do go doc,
ec2 -> aws instances -> arguement reference
------------------


using yesterdays' code, we use accessa_key and secret_key.

static credential is not recommended.

use
> aws configre     # to configure profile  # gogole aws create profile
> aws configure list-profile


provider "aws" {

region = "ap-south-1"
profile = myprofile"

}

resouce "aws_instance" "os1" {

ami = "ami...."
instance_type = "t2.micro"
tags = {
  Name = "My OS - II"
  }
}

os1 is a varible where it keeps all the info about all the variable.

note: if you create code on new folder, you have to initialize so that it will download the plug-in needed,
> terraform init
> terrafrom plan
> terraform apply


how do we get the region name so that we can attach the volume at the same region.


all variable info is stored at 'aws_instance.os1' variable.
we can use output function to print the value.

This is how we printed the value.

$ cat ec2.tf
variable "x" {
  type = string    # value of string is string
  default = "Terraform Training"    # define the default value.
}

output "myvalue" {
  value = "${var.x}"
}


so we can do it

output "os1" {
   value = aws_instance.os1
}

lets put together

provider "aws" {

region = "ap-south-1"
profile = myprofile"

}

resouce "aws_instance" "os1" {

ami = "ami...."
instance_type = "t2.micro"
tags = {
  Name = "My OS - II"
  }
}

output "os1" {
   value = aws_instance.os1
}

> tf apply

you will see it print out everything
review the output.

you will se ami
availibity zone

public_ip

you can see all the variable, value here without going to aws.

you can login to aws console and ec2. verify ip, az and more info..

they are same.

print the public IP

edit the code and add the entry below

output "my_public_ip_is" {
# output "my_availibilibity_is" {

# availibility_zone
#value = aws_instance.os1.availbility_zone
value = aws_instance.os1.public_ip
}

> terraform apply

go to document
click on ec2
- Resources
- Data sources

click on data source
click on aws_instance

look for argument reference


now, we have to create a volume and attach.
but we have to create on specific az.


go to docs,
go to ec2 -> resource and search for ebs volume
aws_ebs_volume
click and look at the example

resource "aws_ens_volume" "st1" {

 vaailability_zone = "us-west-2a"    # review the region
 size = 10

tags = {
   Name = New Hradidisk"
}
}

we can't hardcode the value, use variable

resource "aws_ens_volume" "st1" {

 vaailability_zone = "aws_instance.os1.availibity_zone"    # review the region
 size = 10

  tags = {
    Name = New Hradidisk"
 }
}


put together and run
> tf apply

go to aws ebs, you will see the volumes



-------------------
resouce "aws_instance" "os1" {

ami = "ami...."
instance_type = "t2.micro"
tags = {
  Name = "My OS - II"
  }
}

output "my_az_is" {

  value = aws_instance.os1.availability_zone
}

resource "Aws_ebs_volume" "st1" {

  availbility_zone = aws_instance.os1.availability_zone
  size               = 10

  tags = {
    Name = New Hradidisk"
  }
}

output "o2" {
  value = aws_ebs_volume.st1.id
}


now, attach

your os and hard disk need to be on same az, same region.


one more resource we going to add

go to docs, look for resource which helps to attach the volume

aws_volume_attachment
review the example

go to arguement reference
you have to specify the device name

# Step3
resource "aws_volume_attachment" "ens_att" {
  device_name = "/dev/sdh"
  volume_id = aws_ens_volume.st1.id
  instance_id = aws_instance.os1.id
}


> tf apply

dynamically create os, volume and attach..

now, go to your aws console -> go to the instance, you will see the instance with added disk..


destroy

destroy attachment, volume and shutdown instance..and destroy

once click creates (tf apply)
one click destroys entire infrastructure (tf destroy)





Wednesday, May 5, 2021

Day2 - Terraform - Creating an EC2 instance using terraform

 github.com/zealvora/terraform-beginner-to-advanced-resource

👉  What is terraform registry...?
- Terraform registry enables the distrubution of terraform modules which are reusable configurations.
In fact, it is the place where we store all the information about the service providers and modules.
All the provider information is stored in Terraform registry. We can get example, code/documentaton details of all supported applications.

👉 What is the role of terraform init command...?
- The terraform init command is used to initialize the working directory containing terraform written code (or config files), and on the basis of that code, it will download the respective provider plugin like aws, gcp etc. This is the first command you run after writing your terraform configuration code.
To use a provider or module from the registry, simply add it to your configuration using the "terraform init" command, and Terraform will download anything it needs automatically.

👉 What are providers and resources in terraform...?
- Providers are cloud platform/applications that provides Infrastructure-as-a-Service for eg, aws, gcp that are supported by terraform. They come with plugins which is used to interact with the remote system.
The providers are the one who provide their services to us.

Resources are the sub-services provided by the cloud provides such as VPC, EC2, EBS in terraform. Resources are the most important element in the terraform, each resource block describes one or more infrastructure objects. Terraform resources are implemented by provider plugins. The terraform registry is the main directory of the publicly available terraform providers.

👉 what is the difference between imperative and declarative language...?
- Imperative language is like a Procedural language where steps plays an important role whereas in declarative language we are more focus on the final output rather than it's steps.
So, you can say, imperative language simply describes the control flow of computation and remmebers the state. Declarative programming simply expresses the logic of computation and have no knowledge of state of program.
Thats being said, you basically specify all the information that need to perform all the activity. Even the code is already implemented or executed earlier, if you run again, it will run and go throug the build process. These code may lack the intelligence. whicle in case of declrative language, you give some information about the infrascture, they will understand what to do. Once you execute the code, it will do everything it need to do. But if you rerun again, it will not execute if there is no change on the code. They are intelligent enough the tell you that the code you already executed has not new change.

 day2 - Terraform 5-5-2021

TF -> AWS (cloud) -> Provision server or other job

Code
-----
-----
-----
-----

write instruction (program)
- automation

Go to the site below to find the providers TF supports

https://registry.terraform.io

- broswer providers
- select aws


go to your windows machine
> mkdir terraform-ws
> cd terraform-ws
> mkdir basic; cd basic
> notepad first.tf
provider "aws {}    #

we are telling terraform, we want to do something on aws.
- detech aws, auto detech the provider and download the plugin.
- if you run this program again and again innfuture, you don't have to download


> dir
> terraform init    # you run this command first time.
they will automatically download the plugin

> cd .terraform\providers\registry.terraform.io\hashicorp\aws\3.38.0\windows_aws64
you will find the plugin this place
> dir

---------------------------------
something to know about aws
- Go to aws and create an account and copy seccret key and access key
- AWS works on region
- EC2 - Instance/OS/VM/server (azure also has simiar name)
  - inside the server, you have sub-services
    (volue, netwrok, load balance, security and more)
    (for os you need RAM/CPU/HD/Network ....)
  in terraform term, these sub-services are called resources.

- lets go to ec2 dashboard and
- click on instance
- click on launch new instance
- select OS (select amazon linux-2 -> copy ami-id...
- instance type - copy the type name t2.micro
- next configure instance detail, leave default
- next -> tag -> name=os3
- next security (leave default)
- click and launch
- proceed without a key pair (default setting)
These are the basic steps and we collect these steps. we have to convert these steps into terraform code.

everything you do manuall graphically, you have to copy every single step into code.

How do we know what keyword do they use on terraform.
First we collect the required fields. and go to terraform.

go to aws providers.
click on terraform aws documentation
click on AWS provider

on the right side, you see authentication
- static
you will see an example..


go to ec2 resources on left side
- go through and look for aws instance
- click on it, you will see  
  Resource: aws_instance
it says provides and go through the examples...

you are look for arguements..
- look for AMI
  - it says ami is required keyword
  - public_ip_address is optional .
  - look for fields required fields or optional ones.

- go down to tags
  - its an optional field as well

you can also click on example on right side to find more...

go to aws IAM and create a user. (give power use access power)
-
-----------------------------------------------

back to the basic on TF
> notepad terraform.tf

provider "aws" {

region = "ap-south-1"
access_key = "ABCHDDHHFHIE77lhHHGSLSLDH"
secret_key = "AJKLFJKLJDKJFKDJI3338kjjh"

}

resource "ec2 instance" {

image id ="ami-01938d8s003ds88ss"
instance type = "t2.micro"
tags Name = os4


}
 
-------------------------
now, correct the terms

> notepad terraform.tf
provider "aws" {

region = "ap-south-1"
access_key = ""
secret_key = ""

}

resource "ec2 instance" "os1" {    # os1 is resource name

ami ="ami-01938d8s003ds88ss"
instance_type = "t2.micro"
tags = {
  Name = "My first OS RHEL"
    }
}
 
Note: tag is a map (dictionary) and defined in key/value format.

terraform creates and also manages the respources.

state: currect/desire state

Now, run this code

> terraform init
> terrafrom apply    # executing the code

apply checks the code, plan code and executes
this will basically create an instance on AWS.

it will prompt, just type yes and press enter

go to aws console, you will see the instance running..



declarative language


let go ahead and make change to code

> notepad terraform.tf
provider "aws" {

region = "ap-south-1"
access_key = ""
secret_key = ""

}

resource "ec2 instance" "os1" {    # os1 is resource name

ami ="ami-01938d8s003ds88ss"
instance_type = "t2.micro"
tags = {
  Name = "My first OS New"
    }
}
> terraform apply
@prompt say: yes

it will change the name..

lets say we want to change t2.micro to other one?
yes, how?

go to instance -> action -> instance -? change instance state
it grayed out.

to change, you have to shutdown the instance, and change the instance type.


but for terraform, lets just change the name


> notepad terraform.tf
provider "aws" {

region = "ap-south-1"
access_key = ""
secret_key = ""

}

resource "ec2 instance" "os1" {    # os1 is resource name

ami ="ami-01938d8s003ds88ss"
instance_type = "t2.small"
tags = {
  Name = "My first OS New"
    }
}
> terraform apply




Updating gitlab-ee and gitlab-runner

 1. Download software
gitlab-ee
gitlab-runner

2. Copy software to repo server and create a repo
# cd /software/repo
createrepo

3. Check for update
# yum --enablerepo=* clean all
# yum search gitlab
# yum check-update

# yum versionlock list
# yum versionlock delete gitlab-ee gitlab-runner
# yum versionlick list

4. Update the software
# yum update -y
# yum versionlock add gitlab-ee gitlab-runner

-----------------------------------------------

$ eval $(ssh-agent)
$ ssh-add ~kamal/.ssh/id_rsa

$ ansible -i host-list all -o -a "rpm -q gitlab-ee" | grep CHANGED

This command lists all the systems which has gitlab-ee (Repo). You may have server on test and prod.

$ ansible -i host-list all -o -a "rpm -q gitlab-runner" | grep CHANGED

runner is a ci/cd program like Jinkins. You wil have couple of servers and need to update them as well.

Once you identify the list of servers, coordinate with developers/operation folks for downtime to implement the change.



Tuesday, May 4, 2021

Killing Zombie Processes

 
Zombie process

Zombie process is a dead process which not cleaned up properly so still has an entry to the process table. In fact when child process execution is completed but its not able to send the exit status to the parent process. Parent process still wait for the exist status from the child process. It is a good practice to clean/kill the defunct process.


1. How to find zombie process?

$ top -b1 -n1 | grep Z
or
$ ps aux | grep Z
or
$ ps aux | grep def

2. Find parent process of zombie process
$ ps -A -ostat,ppod | egrep '[zZ]' awk '{print $2}' | uniq | xargs ps -p
or
$ ps axo stat,ppid,pid,comm | grep -w defunct

3. send SIGCHLD process to parent process
$ kill -s SIGCHLD <PPID>
or
$ ps axo stat,ppid,pid,comm | awk '{ print $2}' | uniq | xargs kill -9
$ top -b1 -n1 | grep Z
or
kill -9 <PPID>

to kill

$ ps -af | grep def

kill the parent process

$ kill -9 <P-PID>


Git branch show detached HEAD

  Git branch show detached HEAD 1. List your branch $ git branch * (HEAD detached at f219e03)   00 2. Run re-set hard $ git reset --hard 3. ...