❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdaymanimaran990

AWS EBS

21 November 2023 at 01:09

Elastic Block Store

Block storage service, N number of block storages can be attached to one instance. Just like additional storage.

  • Create an EC2 instance
  • Create a volumne from dashboard
  • Select and attach that volumne to an instance

df -Th

dc16d6291719b2818d8c52ce1ccc6ecf.png

lsblk

46c67f7840f07bcc11a75c376b2ba168.png

sudo file -s /dev/xvdf

ac058855ce6414a1fa6a1817936f3108.png

To format

sudo mkfs -t ext4 /dev/xvdf

f49d471f4142056db5e8b2d7e2759da3.png

To mount:

sudo mkdir /data

sudo file -s /dev/xvdf

sudo mount /dev/xvdf /data

df -Th
3f7fe450331b8ce5c7bc22609c623d9b.png

To permanently mount them on on startup:

sudo cp /etc/fstab /etc/fstab.bak

sudo blkid

sudo vi /etc/fstab

add entry: /dev/xvdfΒ  Β  /dataΒ  Β  Β  ext4Β  Β  Β defaults,nofail 0 2

80a3dbab43901f98047b0208b7e35cd1.png

To unmount

sudo umount /data

Billing calculator

https://calculator.aws/#/addService/EBS

AWS Lightsail

18 November 2023 at 01:09

Lightsail

  • Quickly spinup linux servers
  • low cost
  • Per month plan
  • No security groups
  • Dynamic IP will be provided on each start

Getting started

  • Console > search Lightsail
  • Comes with OS or Bundled with APP
  • Create new SSH key pair
  • Choose plan and create instance

ssh -i mykey.pem ubuntu@publicip

Static IP

Network > Create a static IP
Those static IPs should be attached to instance

Attach EBS to Lightsail instance

  • Create Lightsail Instance
  • Click Storage - Create disk
  • Create a disk
  • Attach disk to active instance
  • format and mount the file system via shell
  • add an entry in /etc/fstab to mount it on system startup

To delete volumne

  • Stop the instance
  • detach the volumne
  • delete the volumne

AWS EC2

17 November 2023 at 01:20

AWS EC2 Quick-start

EC2 > Instances > Launch an instanec

  • Name : demo-ubuntu
  • Application and OS Images - Ubuntu
  • AMI - Ubuntu Server
  • Architecture - 64bit
  • Instance type - t2.micro
  • key pair (login) - generate key
  • Network settings - edit
  • Augo-assign public IP - Enable
  • Firewall (seucurity groups) - create security group
  • Configure storage - 1x 8 GB
  • Launch Instance

By default pem key permission with 664

$ stat -c %a demo-key.pem
664

To change pem key read/write permission only to user

$ sudo chmod 600 demo-key.pem

ssh -i demo.key.pem ubuntu@public\_ip

sudo passwd root

sudo apt update

To check the public IP

curl icanhazip.com

curl ifconfig.me

curl http://checkip.amazonaws.com

To install apache2 server

sudo apt install apache2 -y

enable, start and check status of service

sudo systemctl start apache2

sudo systemctl enable apache2

sudo systemctl status apache2

To enable port 80

EC2 > Security Groups > Edit Inbound Rules > add port 80

IP

By default dynamic IP will be given

5 Elastic(static) IP can be given free
if those IPs are inactive it will be charged for that idle time

install app

sudo apt install apache2 -y

sudo systemctl enable apache2
sudo systemctl start apache2
sudo systemctl status apache2

Access the public IP in browser

To allow http change the security groups

EC2 > Security Groups > Add Rule > add http port 80

Now access the ip in browser, server will be up and running

AWS Services

9 November 2023 at 19:18

S3 - Simple Storage Service

Using amazon S3 we can store and retrieve any amount of data from anywhere, also store any type of data.

bucket is a container for objects

objects any type of file and any metadata that describes the file

used to store photos/videos also host static websites

Amazon Elastic Compute Cloud

Amazon Elastic Compute Cloud, or amazon EC2, is a web service that provides reliable, scalable, compute capacity in the cloud so that you can launch virtual servers in minutes.

Amazon RDS

Relational Database Service(RDS), which is fully managed and removes the need for manual database infrastructure provisioning and maintenance.

Amazon RDS automates backups, database snapshots and host replacement to reduce the administrative burden.

To achieve high availability, deploy your database across multiple availability zones(AZs). In a mutil-AZ deployment, Amazon RDS automatically creates a primary DB instance and

synchronously replicates the data to an instance in a different AZ

Β 

Amazon DynamoDB

key, value and document database

NoSQL DB, no need of schema, automatically scales, and single digit millisecond latency

support partiion key only or partition key+sort key

Amazon EFS

Elastic File System is a serverless, set and forget solution that you can use to share file data without provisioning or managing storage.

Using Amazon EFS, we can create shared network drives so that your branches can access pet client photos from a central location, and you can restrict access with file-level permissions.

Amazon EFS provides petabyte-scale storage that grows and shrinks automatically as you add and remove files.

EFS is highly available and high percent durability. EFS object is redundantly stored across multiple availability zones. It's designed to sustain concurrent device failures by quickly detecting and repairing any lost redundancy

Puppet Deployment

4 November 2023 at 18:15

Install Packages

cd /etc/puppet/code/environments/production/modules/packages

cat manifests/init.pp

class packages {
    package { 'python-requests':
        ensure => installed,
    }

}

sudo chmod 646 manifests/init.pp

class packages {
   package { 'python-requests':
       ensure => installed,
   }
   if $facts[os][family] == "Debian" {
     package { 'golang':
       ensure => installed,
     }
  }
   if $facts[os][family] == "RedHat" {
     package { 'nodejs':
       ensure => installed,
     }
  }
}

sudo puppet agent -v --test

Fetch machine information

cat manifests/init.pp

class machine_info {
  if $facts[kernel] == "windows" {
       $info_path = "C:\Windows\Temp\Machine_Info.txt"
   } else {
       $info_path = "/tmp/machine_info.txt"
   }
 file { 'machine_info':
       path => $info_path,
       content => template('machine_info/info.erb'),
   }
}

Puppet Templates

  • Embedded Puppet (EPP) uses Puppet expressions in special tags. It's easy for any Puppet user to read, but only works with newer Puppet versions. (β‰₯ 4.0, or late 3.x versions with future parser enabled.)
  • Embedded Ruby (ERB) uses Ruby code in tags. You need to know a small bit of Ruby to read it, but it works with all Puppet versions.

cat templates/info.erb

Machine Information
-------------------
Disks: <%= @disks %>
Memory: <%= @memory %>
Processors: <%= @processors %>
Network Interfaces: <%= @interfaces %>
}

Run this in puppet agent

sudo puppet agent -v --test

Reboot machine

sudo mkdir -p /etc/puppet/code/environments/production/modules/reboot/manifests

cd /etc/puppet/code/environments/production/modules/reboot/manifests

sudo touch init.pp

sudo nano init.pp

Ways to reboot each OS

  • shutdown /r on windows
  • shutdown -r now on Darwin (macOS)
  • reboot on Linux.

The complete reboot/manifests/init.pp should now look like this:

class reboot {
  if $facts[kernel] == "windows" {
    $cmd = "shutdown /r"
  } elsif $facts[kernel] == "Darwin" {
    $cmd = "shutdown -r now"
  } else {
    $cmd = "reboot"
  }
  if $facts[uptime_days] > 30 {
    exec { 'reboot':
      command => $cmd,
     }
   }
}

So, edit /etc/puppet/code/environments/production/manifests/site.pp using the following command:

node default {
   class { 'packages': }
   class { 'machine_info': }
   class { 'reboot': }
}

Run the client on linux-instance VM terminal:

sudo puppet agent -v --test

Puppet in Local

3 November 2023 at 02:03

sudo apt install puppet-master

Manifest - ends with .pp

(base) mani@mani-lappy:~/puppet$ cat tools.pp
package { 'htop':
  ensure => present,
}

sudo puppet apply -v tools.pp

Resource Relationship

class ntp {
  package { 'ntp':
    ensure => latest,
  }
  file { '/etc/ntp.conf':
    source => '/home/user/ntp.conf',
    replace => true,
    require => Package['ntp'],
    notify => Service['ntp'],
  }
  service { 'ntp':
    enable => true,
    ensure => running,
    require => File['/etc/ntp.conf'],
 }
}

include ntp

Organizing Puppet Modules

A module is an easy way to organize our configuration management tools.

Puppet Nodes

Different kinds of nodes are defined, allowing different sets of rule catalogs to apply to different types of machines.

node definitions are stored in site.pp

Deploying Puppet to Clients

puppet parser validate

The puppet parser validate command checks the syntax of the manifest to make sure it's correct.

Puppet

2 November 2023 at 16:46

Puppet DSL (Domain Specific Language)

if $facts['is_virtual'] {
  package { 'smartmontools':
  	ensure => purged,
  }
} else {
  package { 'smartmontools':
  	ensure => installed,
  }
}

Β 

Common resources: packages, files and services

fact - A fact is a hash that stores information about the details of a particular system.

Β 

As idempotent action can be performed over and over again without changing the system after the first time the action was performed, and with no unintended side effects.

Β 

Puppet scripts are idempotent, exec is an exception, it will modify the system each time

exec { 'move example file':
  command => 'mv /home/user/example.txt /home/user/Desktop',
  onlyif => 'test -e /home/user/example.txt',
}

To make the execΒ commands to be idempotent, we can use the onlyif

statelessΒ Β it's independent of other actions

Β 

Β 

  • You might remember that every file and directory on a Linux system is assigned permissions for three groups of people: the owner, the group and the others.. And for each group, the permissions refer to the possibility of reading, writing and executing the file.

  • It's common to use numbers to represent the permissions: 4 for read, 2 for write and 1 for execute. The sum of the permissions given to each of the groups is then a part of the final number. For example, a permission of 6 means read and write, a permission of 5 means read and execute, and a permission of 7 means read, write and execute.

  • In this example, we are using 4 numbers. The first one represents any special permissions that the file has (no special permissions). The second one is the permissions for the owner, (read and write), and then come the permissions for the group (read), and finally the permissions for the others (read and write)

Django quick-start

26 October 2023 at 23:50

Create project:

django-admin startproject projectname

To create app in project:

goto projectname
python manage.py startapp hello

to run app:
python manage.py runserver

to store session:
python manage.py migrate

models:
database classess

settings: installed_apps

migrate (to reflect model changes in app):

python manage.py makemigrations

python manage.py sqlmigrate flights 0001

python manage.py migrate

to run shell:

python manage.py shell

from flights.models import Flight

access all data:

Flight.objects.all()

access first:
`f = Flight.objects.first()``

delete:
`f.delete()``

save:
f.save()

admin
python manage.py createsuperuser

creating parameter routes:


  1. add path in urls.py
  2. create that function in views.py
  3. create that template in template folder

link between pages:

  1. give urls a parameter name="index"
    <a href="{% url 'flight' flight.id %}">bla bla</a>

organize html: (template inheritance)

{% extends "base.html" %}

{% block title %} {% endblock %}
{% block body %} {% endblock %}

manyto many relationship models:

models.ManyToManyField(Flight, blank=True, related_name="passengers")

getting form data

  1. get passenger id
    passenger_id = int(request.POST["passenger"])

  2. get passenger and flight by value (model.objects.get(pk=passenger_id))

  3. check for exception
    KeyError and DoesNotExist

  4. add flight to passenger

  5. redirect:
    HttpResponseRedirect(reverse("flight", args=(flight_id, )))

imports

HttpResponseRedirect from django.urls import reverse

submit form

add csrf token in form for security
{% csrf_token %}

django forms:

  1. create forms.py

  2. import
    from django.forms import ModelForm
    from .models import Blog

  3. create class
    class BlogForm(ModelForm):
    class Meta:
    model = Blog
    fields = 'all'

  4. throw form to views (in views.py)
    import .forms import BlogForm
    def index(request):
    form = BlogForm()
    context = { 'form': BlogForm}
    return render(request, 'app/index.html', context)

  5. add it in template
    {{ form }}

tags:
[[django]] [[python]] [[django]]

Django roadmap

26 October 2023 at 23:50

Django roadmap

Django Cheatsheet

26 October 2023 at 23:50
  1. Install Django:

    Copy code

    pip install django

  2. Create a Django project:

    Copy code

    django-admin startproject project_name

  3. Create a Django app:

    Copy code

    python manage.py startapp app_name

  4. Run the development server:

    Copy code

    python manage.py runserver

  5. Database migrations:

    Copy code

    python manage.py makemigrations python manage.py migrate

  6. Create a Django model:

    pythonCopy code

    from django.db import models
    
    class ModelName(models.Model):     
        field_name = models.FieldType(options)
  7. Register a model with Django admin:

    pythonCopy code

    from django.contrib import admin 
    from .models import ModelName  
    
    admin.site.register(ModelName)
  8. Create a Django view:

    pythonCopy code

    from django.http import HttpResponse
    
    def view_name(request):
        return HttpResponse("Hello, World!")
  9. Create a URL pattern:

    pythonCopy code

    from django.urls import path from . import views  
    urlpatterns = [ path('url_path/', views.view_name, name='url_name'), ]
  10. Render a Django template:

from django.shortcuts import render
def view_name(request):
        return render(request, 'template_name.html', context)
  1. Use Django template tags and filters:
cssCopy code

`{% tag %} {{ variable|filter }}`
  1. Create a Django form:
from django import forms from .models
import ModelName  
class FormName(forms.ModelForm):
    class Meta:
        model = ModelName
        fields = ['field1', 'field2']
  1. Use Django forms in templates:
<form method="post">     {% csrf_token %}     {{ form.as_p }}     <button type="submit">Submit</button> </form>
  1. Django authentication views and URLs:
django.contrib.auth.views.LoginView
django.contrib.auth.views.LogoutView  
django.contrib.auth.views.PasswordChangeView
django.contrib.auth.views.PasswordResetView

ETL Shell commands

26 October 2023 at 23:50

ETL Shell commands

cut

echo "database" | cut -c1-4
echo "database" | cut -c5-8Β Β  --> from 5 to 8
echo "database" | cut -c1,5Β Β  --> cut char 1 and 5

extract fields:

cut -d":" -f1 /etc/passwdΒ Β  --> field 1
cut -d":" -f1,3,6 /etc/passwdΒ Β  --> field 1,3 and 6
cut -d":" -f3-6 /etc/passwdΒ  --> field 3 to 6

tr

echo "Shell Scripting" | tr "[a-z]" "[A-Z]"
echo "Shell Scripting" | tr "[:lower:]" "[:upper:]"
echo "Shell Scripting" | trΒ  "[A-Z]" "[a-z]"

Squeeze repeating occurrences of characters:

ps | tr -s " "
ps | tr -s "[:space:]"

Delete characters:

echo "My login pin is 5634" | tr -d "[:digit:]"

Tags:
#etl, #ibm, #shell

Shell basics - cheatsheet

26 October 2023 at 23:50

Shell basics - cheatsheet

return your user name

whoami

return your user and group id

id

return operating system name, username, and other info

uname -a

display reference manual for a command

man top

get help on a command

curl --help

return the current date and time

date


Monitoring performance and status

list selection of or all running processes and their PIDs

ps
ps -e

display resource usage

top

list mounted file systems and usage

df


Working with files

copy a file

cp file.txt new_path/new_name.txt

change file name or path

mv this_file.txt that_path/that_file.txt

remove a file verbosely

rm this_old_file.txt -v

create an empty file, or update existing file's timestamp

touch a_new_file.txt

change/modify file permissions to 'execute' for all users

chmod +x my_script.sh

get count of lines, words, or characters in file

wc -l table_of_data.csv
wc -w my_essay.txt
wc -m some_document.txt

return lines matching a pattern from files matching a filename pattern - case insensitive and whole words only

grep -iw hello *.txt

return file names with lines matching the pattern 'hello' from files matching a filename pattern

grep -l hello *.txt

Navigating and working with directories

list files and directories by date, newest last

ls -lrt

find files in directory tree with suffix 'sh'

find -name '*.sh'

return present working directory

pwd

make a new directory

mkdir new_folder

change the current directory: up one level, home, or some other path

cd ../
cd ~ or cd
cd another_directory

remove directory, verbosely

rmdir temp_directory -v


Printing file and string contents

print file contents

cat my_shell_script.sh

print file contents page-by-page

more ReadMe.txt

print first N lines of file

head -10 data_table.csv

print last N lines of file

tail -10 data_table.csv

print string or variable value

echo "I am not a robot"
echo "I am $USERNAME"

Compression and archiving

archive a set of files

tar -cvf my_archive.tar.gz file1 file2 file3

compress a set of files

zip my_zipped_files.zip file1 file2
zip my_zipped_folders.zip directory1 directory2

extract files from a compressed zip archive

unzip my_zipped_file.zip
unzip my_zipped_file.zip -d extract_to_this_direcory


Performing network operations

print hostname

hostname

send packets to URL and print response

ping www.google.com

display or configure system network interfaces

ifconfig
ip

display contents of file at a URL

curl

download file from a URL

wget

Bash shebang
\#!/bin/bash

Pipes and Filters

chain filter commands using the pipe operator

ls | sort -r

pipe the output of manual page for ls to head to display the first 20 lines

man ls | head -20

Shell and Environment Variables

list all shell variables

set

define a shell variable called my_planet and assign value Earth to it

my_planet=Earth

display shell variable

echo $my_planet

list all environment variables

env

environment vars: define/extend variable scope to child processes

export my_planet

export my_galaxy='Milky Way'

Metacharacters

comments

# The shell will not respond to this message

command separator

echo 'here are some files and folders'; ls

file name expansion wildcard

ls *.json

single character wildcard

ls file_2021-06-??.json

Quoting

single quotes - interpret literally

echo 'My home directory can be accessed by entering: echo $HOME'

double quotes - interpret literally, but evaluate metacharacters

echo "My home directory is $HOME"

backslash - escape metacharacter interpretation

echo "This dollar sign should render: $"


I/O Redirection

redirect output to file

echo 'Write this text to file x' > x

append output to file

echo 'Add this line to file x' >> x

redirect standard error to file

bad_command_1 2> error.log

append standard error to file

bad_command_2 2>> error.log

redirect file contents to standard input

$ tr β€œ[a-z]” β€œ[A-Z]” < a_text_file.txt

the input redirection above is equivalent to

$cat a_text_file.txt | tr β€œ[a-z]” β€œ[A-Z]”


Command Substitution

capture output of a command and echo its value

THE_PRESENT=$(date)
echo "There is no time like $THE_PRESENT"

Command line arguments
./My_Bash_Script.sh arg1 arg2 arg3

Batch vs. concurrent modes

run commands sequentially

start=(date);./MyBigScript.sh;end=(date); ./MyBigScript.sh ; end=(date)

run commands in parallel

./ETL_chunk_one_on_these_nodes.sh & ./ETL_chunk_two_on_those_nodes.sh


Scheduling jobs with Cron

open crontab editor

crontab -e

job scheduling syntax

m h dom mon dow command
minute, hour, day of month, month, day of week

  • means any

append the date/time to file every Sunday at 6:15 pm

15 18 * * 0 date >> sundays.txt

run a shell script on the first minute of the first day of each month

1 0 1 * * ./My_Shell_Script.sh

back up your home directory every Monday at 3 am

0 3 * * 1 tar -cvf my_backup_path\my_archive.tar.gz $HOME\

deploy your cron job

Close the crontab editor and save the file

list all cron jobs

crontab -l

$ declare -a myArray
$ myArray+=("Linux")
$ myArray+=("is")
$ myArray+=("cool!")
$ echo ${myArray[@]}
❌
❌