Tuesday, 19 December 2023
Data Integrity Kafka
Tuesday, 7 June 2022
Waf-v2 as module
Monday, 9 May 2022
Waf-v2 as resource
Wednesday, 22 December 2021
CircleCI Orbs
Terraform user with secrets in aws secret manager
data "aws_iam_policy_document" "ci_user_s3_policy" {
statement {
actions = [
"s3:DeleteObject",
"s3:DeleteObjectTagging",
"s3:DeleteObjectVersion",
"s3:DeleteObjectVersionTagging",
"s3:ListBucket",
"s3:GetObject*",
"s3:PutObject*",
"s3:ReplicateObject",
"s3:RestoreObject"
]
resources = [
"arn:aws:s3:::ansible-bucket-${var.environment}/*",
"arn:aws:s3:::ansible-bucket-${var.environment}"
]
}
}
variable "environment" {
type = string
}
variable "vaultpass" {
type = string
}
resource "aws_s3_bucket" "ansible_bucket" {
bucket = "ansible-bucket-${var.environment}"
acl = "private"
force_destroy = true
}
resource "aws_iam_user" "user" {
name = "ansible-ci-upload"
}
resource "aws_iam_access_key" "ansible_repo" {
user = aws_iam_user.user.name
}
resource "aws_iam_policy" "ci_user_s3_policy" {
policy = data.aws_iam_policy_document.ci_user_s3_policy.json
}
resource "aws_iam_user_policy_attachment" "attach-policy" {
user = aws_iam_user.user.name
policy_arn = aws_iam_policy.ci_user_s3_policy.arn
}
resource "aws_secretsmanager_secret" "ansible_credentials" {
name = "ansible-circleci-user-creds"
}
resource "aws_secretsmanager_secret" "ansible_git_credentials" {
name = "ansible-git-creds"
}
resource "aws_secretsmanager_secret_version" "ansible_credentials" {
secret_id = aws_secretsmanager_secret.ansible_credentials.id
secret_string = jsonencode({
access_key = aws_iam_access_key.ansible_repo.id
access_secret = aws_iam_access_key.ansible_repo.secret
vault_pass = var.vaultpass
})
}
resource "aws_secretsmanager_secret_version" "ansible_credentials_key" {
secret_id = aws_secretsmanager_secret.ansible_git_credentials.id
secret_string = file("/mnt/workspace/AnsibleMaster.pem")
}
Thursday, 29 April 2021
Move Existing data to Glacier
#!/bin/bash
> filelist
aws sts get-caller-identity
TARGETBUCKET=$1
echo ''
echo $TARGETBUCKET
echo ''
aws s3 ls $TARGETBUCKET --recursive | awk '{ print $4 }' >> filelist
while read objname
do
aws s3api copy-object --copy-source $TARGETBUCKET/${objname} --bucket $TARGETBUCKET --storage-class GLACIER --key ${objname}
done < filelist
aws s3api list-objects --bucket $TARGETBUCKET --query 'Contents[].{Key: Key, SC: StorageClass}' --output table
Thursday, 11 February 2021
LVM Shorthand
LVM Creation
sudo pvcreate /dev/sda /dev/sdb
sudo vgcreate LVMVolGroup /dev/sda /dev/sdb
sudo lvcreate -L 10G -n test1 LVMVolGroup
sudo lvcreate -l 100%FREE -n test2 LVMVolGroup
sudo mkfs -t ext4 /dev/LVMVolGroup/test1
sudo mkfs -t ext4 /dev/LVMVolGroup/test2
sudo mkdir /vol1
sudo mkdir /vol2
sudo mount /dev/LVMVolGroup/test1 /vol1
sudo mount /dev/LVMVolGroup/test2 /vol2
echo "/dev/LVMVolGroup/test1 /vol1 auto noatime 0 0" | sudo tee -a /etc/fstab
echo "/dev/LVMVolGroup/test2 /vol2 auto noatime 0 0" | sudo tee -a /etc/fstab
sudo mount -a
sudo reboot
Useful Commands:
pvdisplay
vgdiaplay
lvdisplay
Saturday, 26 December 2020
Single Node K8S Cluster
become: yes
tasks:
- name: install gpg
apt:
name: gpg
state: present
update_cache: true
- name: install Docker
apt:
name: docker.io
state: present
update_cache: true
- name: Enable service
service:
name: docker
enabled: yes
- name: start service
service:
name: docker
state: started
- name: install APT Transport HTTPS
apt:
name: apt-transport-https
state: present
- name: add Kubernetes apt-key
apt_key:
url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
state: present
- name: add Kubernetes' APT repository
apt_repository:
repo: deb http://apt.kubernetes.io/ kubernetes-xenial main
state: present
filename: 'kubernetes'
- name: install kubelet
apt:
name: kubelet
state: present
update_cache: true
- name: install kubeadm
apt:
name: kubeadm
state: present
- name: install kubectl
apt:
name: kubectl
state: present
force: yes
- name: Disable SWAP since kubernetes can't work with swap enabled (1/2)
shell: |
swapoff -a
when: ansible_swaptotal_mb > 0
- name: Disable SWAP in fstab since kubernetes can't work with swap enabled (2/2)
replace:
path: /etc/fstab
regexp: '^(.+?\sswap\s+sw\s+.*)$'
replace: '# \1'
- name: initialize the cluster
shell: kubeadm init --pod-network-cidr=10.244.0.0/16 >> cluster_initialized.txt
args:
chdir: $HOME
creates: cluster_initialized.txt
- name: create .kube directory
file:
path: $HOME/.kube
state: directory
mode: 0755
- name: copy admin.conf to user's kube config
copy:
src: /etc/kubernetes/admin.conf
dest: $HOME/.kube/config
remote_src: yes
- name: install Pod network
become: yes
shell: kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d '\n')"
args:
chdir: $HOME
creates: pod_network_setup.txt
- name: Single Node Cluster
shell: kubectl taint nodes --all node-role.kubernetes.io/master-
Tuesday, 10 March 2020
Full Automated Jenkins Pipeline
pipeline {
agent any
stages {
stage('Docker Build') {
steps {
sh '''sed -i "s/appname/${APPNAME}/g; s/relver/v1.${BUILD_NUMBER}/g" ${WORKSPACE}/docker-compose.yml
#sed -i "s/substitute/${JENENV}/g; s/initial/${APPNAME}/g" ${WORKSPACE}/filebeat.yml
sudo docker-compose build
'''
}
}
stage('Docker Push/Pull') {
steps {
sh '''sudo docker-compose push
previous="$((${BUILD_NUMBER}-1))"
sudo docker pull ${REG}/${APPNAME}:v1.$previous || true
if [[ "$(sudo docker images -q ${REG}/${APPNAME}:v1.$previous 2> /dev/null)" != "" ]]; then
sudo docker tag ${REG}/${APPNAME}:v1.$previous ${REG}/${APPNAME}:${RELEASE}
sudo docker push ${REG}/${APPNAME}:${RELEASE}
exit 0
else
:
exit 0
fi
#sudo ssh -T root@${SLAVE} docker login ${REG} -u AraRegistry -p ${ARA_CRED_PSW}
#sudo docker pull ${REG}/${APPNAME}:${RELEASE}
'''
}
}
stage('Anchore Call') {
steps {
build job: 'anchore/Web', parameters: [
string(name: 'IMAGE_NAME', value: String.valueOf(REG) + '/' + String.valueOf(APPNAME) + ':v1.' + String.valueOf(BUILD_NUMBER)),
string(name: 'PARENT_WS', value: String.valueOf(WORKSPACE))
], propagate: false, wait: false
}
}
stage('Secret') {
steps {
sh '''check=$(kubectl get secret -n ${JENENV} | grep ${APPNAME} | awk \'{print $1}\')
if [ -z "$check" ]
then
kubectl apply -f ${MY_CREDENTIAL} -n ${JENENV}
else
kubectl delete secret -n ${JENENV} ${APPNAME}-secret
kubectl apply -f ${MY_CREDENTIAL} -n ${JENENV}
fi
'''
}
}
stage('Deploy') {
steps {
sh '''sed -i "s/JenEnv/${JENENV}/g; s/appname/${APPNAME}/g; s/relver/v1.${BUILD_NUMBER}/g" ${WORKSPACE}/config/deploy.yml
sed -i "s/JenEnv/${JENENV}/g; s/appname/${APPNAME}/g" ${WORKSPACE}/config/service.yml
# Deploy service
kubectl apply -f ${WORKSPACE}/config/service.yml
# Deploy
kubectl apply -f ${WORKSPACE}/config/deploy.yml
sleep 20
# Get rollout status
rolloutStatus=`kubectl rollout status deployment/${APPNAME} -n ${JENENV}`
if [[ $rolloutStatus != *"successfully rolled out"* ]]; then
echo "rollout of ${APPNAME} failed"
exit 1
fi
# Now get the running pods
failingPods=`kubectl get pods --field-selector=status.phase=Running -n ${JENENV} --selector=app=microgateway| wc -l`
if (( $failingPods <= 1 )); then
echo "${APPNAME} pods not running"
exit 1
fi
'''
}
}
stage('Push Version No') {
steps {
sh '''cd /var/lib/jenkins/workspace/${APPNAME}_develop/
echo "${APPNAME}:v1.${BUILD_ID} deployed on $(date)" > last-build-rel-ver.txt
git add last-build-rel-ver.txt
git commit -m "automated version"
git config credential.helper store
git push
'''
}
}
stage('Azure Repo') {
steps {
build job: 'AzureClean/master', parameters: [
string(name: 'PARENT_APPNAME', value: String.valueOf(APPNAME))
], propagate: true, wait: true
}
}
stage('Cleanup') {
steps {
build(job: 'cleanupprod', propagate: true, wait: true)
}
}
}
environment {
MY_CREDENTIAL = credentials('adservice_test')
ARA_CRED = credentials('ara_secret')
KUBECONFIG = '/home/isadmin/.kube/config'
REG = 'araregistry.azurecr.io/ara'
APPNAME = 'adhoc-room-availability'
RELEASE = 'stable'
JENENV = 'prod'
SLAVE = 'box21.ara.ac.nz'
}
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Scanner Call:
pipeline {
agent any
stages {
stage('Analyze') {
steps {
sh 'echo "${IMAGE_NAME} ${PARENT_WS}/Dockerfile" > anchore_images'
anchore(name: 'anchore_images', engineRetries: '5000' )
}
post {
failure {
script {
sh '''job=$(echo ${PARENT_WS} | cut -c 28-)
echo "https://kubeops1.ara.ac.nz:8443/job/anchore/job/${BRANCH_NAME}/${BUILD_NUMBER}/anchore-results/" | mail -s "Build: $job has failed to pass security scan" InfoSystems@ara.ac.nz
'''
}
}
always {
script {
sh '''
for i in `cat anchore_images | awk \'{print $1}\'`;do sudo docker rmi $i; done
'''
}
}
}
}
}
parameters {
string(defaultValue: '', description: 'param1', name: 'IMAGE_NAME')
string(defaultValue: '', description: 'param2', name: 'PARENT_WS')
}
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Repo Call:
pipeline {
agent any
stages {
stage('Clean-Up') {
steps {
sh '''cd ${WORKSPACE}/
taglist=$(sudo ./docker_reg_tool https://${REPO} list ara/${PARENT_APPNAME} | grep 'latest')
for tags in $taglist
do
echo $tags
sudo ./docker_reg_tool https://${REPO} delete ara/${PARENT_APPNAME} $tags
done'''
}
}
}
parameters {
string(defaultValue: '', description: 'param1', name: 'PARENT_APPNAME')
}
environment {
REPO = 'araregistry.azurecr.io'
}
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Wednesday, 7 August 2019
Grafana / Infludb K8s deployment via piepline
Grafana
1. Dockerfile
2. run.sh
3. graf-serv-deploy.yml
4. notification.yml
5. default-dashboard.yml
6. Jenkinsfile
pipeline {
agent any
stages {
stage('Build') {
environment {
KUBECONFIG = '/home/isadmin/.kube/config-mon1'
}
steps {
sh '''sudo docker build -t araregistry.azurecr.io/ara/nashgrafana:latest -f Dockerfile .
sudo docker push araregistry.azurecr.io/ara/nashgrafana:latest'''
}
}
stage('Pull Changes') {
steps {
sh '''sudo ssh -T root@logmon1.ara.ac.nz docker login araregistry.azurecr.io -u AraRegistry -p xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sudo ssh -T root@logmon1.ara.ac.nz docker pull araregistry.azurecr.io/ara/nashgrafana:latest'''
}
}
stage('Deploy') {
steps {
sh '''# Deploy service
kubectl apply -f ${WORKSPACE}/fullgrafana.yml'''
}
}
}
environment {
KUBECONFIG = '/home/isadmin/.kube/config-mon1'
}
}
InfluxdB
1. Dockerfile
FROM influxdb:latest
LABEL description="InfluxDB docker image with custom setup"
USER root
ADD influxdb.template.conf /influxdb.template.conf
ADD run.sh /run.sh
RUN chmod +x /run.sh
CMD ["/run.sh"]
2. Jenkinsfile
pipeline {
agent any
stages {
stage('Build') {
environment {
KUBECONFIG = '/home/isadmin/.kube/config-mon1'
}
steps {
sh '''sudo docker build -t araregistry.azurecr.io/ara/nashflux:latest -f Dockerfile .
sudo docker push araregistry.azurecr.io/ara/nashflux:latest'''
}
}
stage('Pull Changes') {
steps {
sh '''sudo ssh -T root@logmon1.ara.ac.nz docker login araregistry.azurecr.io -u AraRegistry -p xxxxxxxxxxxxxxxxxxx
sudo ssh -T root@logmon1.ara.ac.nz docker pull araregistry.azurecr.io/ara/nashflux:latest'''
}
}
stage('Deploy') {
steps {
sh '''# Deploy service
kubectl apply -f ${WORKSPACE}/fulldeploymentinflux.yml'''
}
}
}
environment {
KUBECONFIG = '/home/isadmin/.kube/config-mon1'
}
}
3. run.sh
4. influx-serv-full.yml
Tuesday, 6 August 2019
Telegraf for K8s Cluster monitering
kubectl create clusterrolebinding default-admin --clusterrole cluster-admin --serviceaccount=default:default
kubectl create secret -n monitoring generic telegraf --from-literal=env=prod --from-literal=monitor_username=youruser --from-literal=monitor_password=yourpassword --from-literal=monitor_host=https://your.influxdb.local --from-literal=monitor_database=yourdb
Daemon apply
apiVersion: v1
kind: ConfigMap
metadata:
name: telegraf
namespace: monitoring
labels:
k8s-app: telegraf
data:
telegraf.conf: |+
[global_tags]
env = "$ENV"
[agent]
hostname = "$HOSTNAME"
[[outputs.influxdb]]
urls = ["$MONITOR_HOST"] # required
database = "$MONITOR_DATABASE" # required
timeout = "5s"
username = "$MONITOR_USERNAME"
password = "$MONITOR_PASSWORD"
[[inputs.cpu]]
percpu = true
totalcpu = true
collect_cpu_time = false
report_active = false
[[inputs.disk]]
ignore_fs = ["tmpfs", "devtmpfs", "devfs"]
[[inputs.diskio]]
[[inputs.kernel]]
[[inputs.mem]]
[[inputs.processes]]
[[inputs.swap]]
[[inputs.system]]
[[inputs.net]]
[[inputs.docker]]
endpoint = "unix:///var/run/docker/libcontainerd/docker-containerd.sock"
[[inputs.kubernetes]]
url = "https://$HOSTNAME:10250"
#bearer_token = "/var/run/secrets/kubernetes.io/serviceaccount/token"
bearer_token_string = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
insecure_skip_verify = true
---
# Section: Daemonset
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: telegraf
namespace: monitoring
labels:
k8s-app: telegraf
spec:
selector:
matchLabels:
name: telegraf
template:
metadata:
labels:
name: telegraf
spec:
containers:
- name: telegraf
image: docker.io/telegraf:latest
resources:
limits:
memory: 500Mi
requests:
cpu: 500m
memory: 500Mi
env:
- name: HOSTNAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: "HOST_PROC"
value: "/rootfs/proc"
- name: "HOST_SYS"
value: "/rootfs/sys"
- name: ENV
valueFrom:
secretKeyRef:
name: telegraf
key: env
- name: MONITOR_USERNAME
valueFrom:
secretKeyRef:
name: telegraf
key: monitor_username
- name: MONITOR_PASSWORD
valueFrom:
secretKeyRef:
name: telegraf
key: monitor_password
- name: MONITOR_HOST
valueFrom:
secretKeyRef:
name: telegraf
key: monitor_host
- name: MONITOR_DATABASE
valueFrom:
secretKeyRef:
name: telegraf
key: monitor_database
volumeMounts:
- name: sys
mountPath: /rootfs/sys
readOnly: true
- name: proc
mountPath: /rootfs/proc
readOnly: true
- name: docker-socket
mountPath: /var/run/docker/libcontainerd/docker-containerd.sock
readOnly: true
- name: utmp
mountPath: /var/run/utmp
readOnly: true
- name: config
mountPath: /etc/telegraf
terminationGracePeriodSeconds: 30
volumes:
- name: sys
hostPath:
path: /sys
- name: docker-socket
hostPath:
path: /var/run/docker/libcontainerd/docker-containerd.sock
- name: proc
hostPath:
path: /proc
- name: utmp
hostPath:
path: /var/run/utmp
- name: config
configMap:
name: telegraf
Wednesday, 31 July 2019
Kubernetes Deployment Via Ansible
- hosts: all
become: yes
tasks:
- name: install gpg
apt:
name: gpg
state: present
update_cache: true
- name: install Docker
apt:
name: docker.io
state: present
update_cache: true
- name: Enable service
service:
name: docker
enabled: yes
- name: start service
service:
name: docker
state: started
- name: install APT Transport HTTPS
apt:
name: apt-transport-https
state: present
- name: add Kubernetes apt-key
apt_key:
url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
state: present
- name: add Kubernetes' APT repository
apt_repository:
repo: deb http://apt.kubernetes.io/ kubernetes-xenial main
state: present
filename: 'kubernetes'
- name: install kubelet
apt:
name: kubelet
state: present
update_cache: true
- name: install kubeadm
apt:
name: kubeadm
state: present
- hosts: master
become: yes
tasks:
- name: install kubectl
apt:
name: kubectl
state: present
force: yes
/etc/ansible/playbook/master.yaml
- hosts: master
become: yes
tasks:
- name: Disable SWAP since kubernetes can't work with swap enabled (1/2)
shell: |
swapoff -a
when: ansible_swaptotal_mb > 0
- name: Disable SWAP in fstab since kubernetes can't work with swap enabled (2/2)
replace:
path: /etc/fstab
regexp: '^(.+?\sswap\s+sw\s+.*)$'
replace: '# \1'
- name: initialize the cluster
shell: kubeadm init --pod-network-cidr=10.244.0.0/16 >> cluster_initialized.txt
args:
chdir: $HOME
creates: cluster_initialized.txt
- name: create .kube directory
become: yes
file:
path: $HOME/.kube
state: directory
mode: 0755
- name: copy admin.conf to user's kube config
copy:
src: /etc/kubernetes/admin.conf
dest: $HOME/.kube/config
remote_src: yes
- name: install Pod network
become: yes
shell: kubectl apply -f "https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d '\n')"
args:
chdir: $HOME
creates: pod_network_setup.txt
Wednesday, 29 May 2019
Reverse Engineer a docker image for Dockerfile
if [[ "$(docker images -q chenzj/dfimage:latest 2> /dev/null)" == "" ]]; then
docker pull chenzj/dfimage
fi
read -e -p "Enter Image ID: " IMAGE_ID
if grep -q dfimage /etc/profile;
then
:
else
echo "" >> /etc/profile
echo alias dfimage="'docker run -v /var/run/docker.sock:/var/run/docker.sock --rm chenzj/dfimage'" >> /etc/profile
source /etc/profile
fi
docker run -v /var/run/docker.sock:/var/run/docker.sock --rm chenzj/dfimage $IMAGE_ID > Dockerfile1
docker history --no-trunc $IMAGE_ID | tac | tr -s ' ' | cut -d " " -f 5- | sed 's,^/bin/sh -c #(nop) ,,g' | sed 's,^/bin/sh -c,RUN,g' | sed 's, && ,\n & ,g' | sed 's,\s*[0-9]*[\.]*[0-9]*[kMG]*B\s*$,,g' | head -n -1 > Dockerfile2
Wednesday, 22 May 2019
Systemd Service only initiates at shutdown ( no reboot ) and keeps network intact
[Unit]
Description=Run a Bash script at shutdown
DefaultDependencies=no
Wants=network-online.target
After=network-online.target
Before=poweroff.target halt.target
[Service]
ExecStart=/usr/bin/curl -X POST 'http://box21.ara.ac.nz:32446/query?db=telegraf' --data-urlencode "q=DROP SERIES WHERE host = '%H'"
Type=oneshot
RemainAfterExit=yes
[Install]
WantedBy=poweroff.target halt.target
Monday, 29 April 2019
Reboot and Volume detach/attach
#!/usr/bin/env bash
if [ ! -f /home/resume-after-reboot ]; then
function sqlkiller {
while :
do
sqlstatus=$(systemctl status mysql | awk 'FNR == 3 {print $2}')
if [[ "${sqlstatus}" == "active" ]]; then
break
else
/etc/init.d/mysql start
sleep 5s
continue
fi
done
}
function createnewvol {
while :
do
progress=$(aws ec2 describe-snapshots --snapshot-id $snapid --query "Snapshots[*].{Cond:State}" --output text --region us-east-1)
if [[ "${progress}" == "completed" ]]; then
freshvol=$(aws ec2 create-volume --region us-east-1 --availability-zone us-east-1d --snapshot-id $snapid --volume-type gp2 --output text | awk '{print $8}')
touch /home/freshvol.txt
echo $freshvol > /home/freshvol.txt
sleep 2m
break
else
continue
fi
done
}
function searchsnap {
for ((i=0;i<5;i++))
do
current=$(date +%Y%m%d -d "-$i days")
snapid=$(aws ec2 describe-snapshots --filters Name=description,Values=""$value"_$current" --query "Snapshots[*].{SD:SnapshotId}" --region us-east-1 --output text)
if [[ $snapid == *"snap-"* ]]; then
echo "Snapshot found - continuing with ID: "$snapid" " >> /var/log/ebs-update.log
createnewvol
break
elif [[ $i -ne 4 ]]; then
continue
else
echo "Snapshot not found - exiting" >> /var/log/ebs-update.log
echo "--" >> /var/log/ebs-update.log
exit 1
fi
exit 1
done
}
while :
do
status=$(pidof mysqld)
if [[ $status -eq 0 ]]; then
echo "Mysql is off - $(date) - Proceeding with updating Database" >> /var/log/ebs-update.log
break
else
sqlkiller
/etc/init.d/mysql stop
pkill -9 mysql
pkill -9 mysqld
pkill -9 mysqld_safe
continue
fi
done
prefix=$(hostname)
value=${prefix#*-}
value="$value-snapshot"
value=$(echo "$value" | sed -r 's/master/slave/g')
instanceid=$(ec2metadata --instance-id)
for letter in /dev/xvdj xvdj /dev/sdj sdj; do
volumeid=$(aws ec2 describe-volumes --filters Name=attachment.instance-id,Values=$instanceid Name=attachment.device,Values=$letter --query "Volumes[*].{ID:VolumeId}" --output text --region us-east-1)
if [ -z "$volumeid" ]; then
continue
else
break
fi
done
fuser -km /dev/xvdj
umount -d /dev/xvdj
fuser -km /dev/sdj
umount -d /dev/sdj
fuser -km /dev/mapper/mysql--product--master-mysql
umount -d /dev/mapper/mysql--product--master-mysql
aws ec2 detach-volume --volume-id $volumeid --region us-east-1 --force
while :
do
status=$(aws ec2 describe-volumes --volume-ids $volumeid --query "Volumes[*].{OP:State}" --output text --region us-east-1)
if [[ "${status}" == "available" ]]; then
searchsnap
break
else
sleep 2m
continue
fi
done
sed -i 's/server.*/server = puppet-master.srv.fish.1/' /etc/puppetlabs/puppet/puppet.conf
script="@reboot root /opt/fishpond/bin/ebs-update"
echo "$script" >> /etc/crontab
touch /home/resume-after-reboot
/sbin/reboot
else
sed -i '/@reboot/d' /etc/crontab
rm -f /home/resume-after-reboot
while :
do
freshvolafter=$(cat /home/freshvol.txt)
instanceidafter=$(ec2metadata --instance-id)
newstatus=$(aws ec2 describe-volumes --volume-ids $freshvolafter --query "Volumes[*].{OP:State}" --output text --region us-east-1)
if [[ "${newstatus}" == "available" ]]; then
aws ec2 attach-volume --volume-id $freshvolafter --instance-id $instanceidafter --device /dev/sdj --region us-east-1
sleep 5m
break
else
continue
fi
done
while :
do
freshvolafterattach=$(cat /home/freshvol.txt)
instanceidafterattach=$(ec2metadata --instance-id)
newstatusattach=$(aws ec2 describe-volumes --volume-ids $freshvolafterattach --query "Volumes[*].{OP:State}" --output text --region us-east-1)
if [[ "${newstatusattach}" == "in-use" ]]; then
break
else
continue
fi
done
mount /dev/mapper/mysql--product--master-mysql /mnt/mysql
mount /dev/xvdj /mnt/mysql
mount /dev/sdj /mnt/mysql
if grep -qs '/mnt/mysql' /proc/mounts; then
logline=$(tail -n2 /var/log/mysql/mysql-error.log | head -1)
if [[ "${logline}" == *"Shutdown complete"* ]]; then
/etc/init.d/mysql start
else
/etc/init.d/mysql restart
fi
sleep 10s
else
mount /dev/mapper/mysql--product--master-mysql /mnt/mysql
mount /dev/xvdj /mnt/mysql
mount /dev/sdj /mnt/mysql
fi
rm -f /home/freshvol.txt
sed -i 's/server.*/server = puppet-master.srv.fish/' /etc/puppetlabs/puppet/puppet.conf
/opt/puppetlabs/bin/puppet agent -t
sleep 5s
echo "Script ran correctly at $(date)" >> /var/log/ebs-update.log
echo "--" >> /var/log/ebs-update.log
fi
Thursday, 18 April 2019
Sync directory - encrypt and move
#!/usr/bin/env bash
echo "Rstudio backup has been started on $(date)" >> /var/log/rstudiobackup.log
dir1="/media/somedirectory/backup-dir"
now=$(date +"%m_%d_%Y_%H")
if [ -d "dir1" ]; then
:
else
mkdir -p /media/somedirectory/backup-dir
fi
rsync -avhz /media/dironserver/dirtobackup/ /media/somedirectory/backup-dir
cd /media/somedirectory
tar -I pigz -cf $now.tar.gz backup-dir
gpg --recipient naveed@nasheikh.com --trust-model always --encrypt --armor $now.tar.gz
mv $now.tar.gz.asc /srv/some-remote-dir
echo "Rstudio backup has been Completed on $(date)" >> /var/log/rstudiobackup.log
echo "--" >> /var/log/rstudiobackup.log
exit 0
Install cron job
crontab -e
30 3 * * SUN /usr/local/bin/backupper.sh
30 3 * * 1-6 /usr/bin/rsync -avhz /media/dironserver/dirtobackup/ /media/somedirectory/backup-dir
Job Finish
Mount checker with email capability
This is done in 3 scripts:
1st Script - the init service:
Mount the directory:
mount -t cifs //192.168.02.02/somedirectory /srv/somedirectory -o vers=3.0,credentials=/root/creds
### BEGIN INIT INFO
# Provides: cifchecker
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Simple script to start a program at boot
# Description: A simple script which will start / stop a program a boot / shutdown.
### END INIT INFO
# If you want a command to always run, put it here
# Carry out specific functions when asked to by the system
case "$1" in
start)
echo "Starting cifchecker"
# run application you want to start
/usr/local/bin/sendemail.sh &
;;
stop)
echo "Stopping cifchecker"
# kill application you want to stop
dead=$(ps -o pgid,cmd -U root | grep -v grep | grep sendemail | awk '{print $1}')
kill -- -$dead
;;
*)
echo "Usage: /etc/init.d/cifchecker {start|stop}"
exit 1
;;
esac
exit 0
Friday, 12 April 2019
Nagios Script
response=$(curl -s http://search-orders.srv.fish:8080/binlog-webapp/binlog?type=status)
tstamp=$(curl -s http://search-orders.srv.fish:8080/binlog-webapp/binlog?type=status| jq '.status' | awk -F'"' '$2=="currentTimestamp"{print $4}')
status=$(curl -s http://search-orders.srv.fish:8080/binlog-webapp/binlog?type=status| jq '.status' | awk -F'"' '$2=="running"{print $4}')
oldstamp=$(date +%s -d "-24 hours")
respinsec=$(date -d "${tstamp}" +"%s")
if [ -z "$response" ]; then
echo "CRITICAL status - No API response"
exit 2
elif [[ "${status}" != "true" ]]; then
echo "CRITICAL status - Search replication is not running."
exit 2
elif (( respinsec < oldstamp )); then
echo "CRITICAL status - Timestamp is over 24 hours."
exit 2
else
echo "OK - Search Replication is running correctly"
exit 0
fi
Wednesday, 10 April 2019
DotNet DockerFile
WORKDIR /app
COPY ./src/AspMVC/publish .
ENTRYPOINT ["dotnet", "AspMVC.dll"]
docker run -p 80:80 myimage
Tuesday, 9 April 2019
Mysql DB backup with lock table system
#!/usr/bin/env bash
WAITFORLOCK=/root/waitlock
WAITFORSNAPSHOT=/root/waitforsnapshot
LOCKTABLERUN=/root/locktables.pid
function locktable {
(
echo "FLUSH TABLES WITH READ LOCK;" && \
sleep 5 && \
touch ${WAITFORSNAPSHOT} && \
rm -f ${WAITFORLOCK} && \
while [ -e ${WAITFORSNAPSHOT} ]; do sleep 1; done && \
echo "SHOW MASTER STATUS;" && \
echo "UNLOCK TABLES;" && \
echo "\quit" \
) | mysql --defaults-file=/root/.my.cnf
rm -f ${LOCKTABLERUN}
}
function prefreeze {
if [ -e ${WAITFORLOCK} ]; then
echo Previous backup failed, waitforlock file still present && exit 1
fi
if [ -e ${WAITFORSNAPSHOT} ]; then
echo Previous backup failed, WAITFORSNAPSHOT file still present && exit 1
fi
if [ -e ${LOCKTABLERUN} ]; then
ps -p `cat ${LOCKTABLERUN}` > /dev/null 2>&1;
if [ $? -eq 0 ]; then
echo Panic, locktables script still running && exit 1
else
rm -f ${LOCKTABLERUN}
fi
fi
touch ${WAITFORLOCK}
locktable &
LOCKTABLEPID=$!
echo ${LOCKTABLEPID} > ${LOCKTABLERUN}
while [ -e ${WAITFORLOCK} ]; do
ps -p ${LOCKTABLEPID} > /dev/null 2>&1;
if [ $? -eq 1 ]; then
break
fi
sleep 1
done
if [ -e ${WAITFORLOCK} ]; then
echo Tablelock script exited without removing waitforlock file, something went wrong
else
echo Tables are locked
fi
}
prefreeze &&
server=$(hostname)
if [[ "${server}" == *"product"* ]]; then
server="db-product-slave-snapshot"
elif [[ "${server}" == *"customer"* ]]; then
server="db-customer-slave-snapshot"
elif [[ "${server}" == *"finance"* ]]; then
server="db-finance-slave-snapshot"
else
server=$(hostname)
fi
instanceid=$(ec2metadata --instance-id)
for letter in /dev/xvdj xvdj /dev/sdj sdj; do
volumeid=$(aws ec2 describe-volumes --filters Name=attachment.instance-id,Values=$instanceid Name=attachment.device,Values=$letter --query "Volumes[*].{ID:VolumeId}" --output text --region us-east-1)
if [ -z "$volumeid" ]; then
continue
else
break
fi
done
snapid=$(aws ec2 create-snapshot --volume-id $volumeid --description ""$server"_$(date +%Y%m%d)" --output text --region us-east-1 | awk '{print $4}')
echo "Backup initiated with SnapshotID: "$snapid"" >> /var/log/ebs-snapshot.log
while :
do
progress=$(aws ec2 describe-snapshots --snapshot-id $snapid --query "Snapshots[*].{Cond:State}" --output text --region us-east-1)
if [[ "${progress}" == "pending" ]]; then
sleep 5m
continue
else
result=$(aws ec2 describe-snapshots --snapshot-id $snapid --query "Snapshots[*].{Cond:State}" --output text --region us-east-1)
echo "Snap has been "$result" and Mysql has been started on $(date)" >> /var/log/ebs-snapshot.log
echo "--" >> /var/log/ebs-snapshot.log
break
fi
done
rm ${WAITFORSNAPSHOT}
exit 0