Pages

Showing posts with label Devops. Show all posts
Showing posts with label Devops. Show all posts

Sunday, 26 July 2026

I built a pipeline to auto-post my Telegram channel everywhere. Then I stopped.

 

Auto-posting my Telegram channel posts everywhere sounded like a dream. Then I actually built it.

The plan was simple. Write one post on my Telegram channel (@securedevops). Let a pipeline pick it up. Reformat it for each platform. Push it out to LinkedIn, Twitter, Instagram, Facebook, Dev.to. Zero manual work after hitting publish once.

I built it in n8n. A webhook catches new posts from the channel. A dedup check makes sure nothing gets posted twice. Then a handoff point where ChatGPT would rewrite the post per platform, and push it live everywhere.

Sounds clean right? It mostly worked. Until it didn't.

Here's where it broke. I was using ngrok's free tier to expose the webhook. Every time my machine restarted, the URL changed. Which meant every time I restarted, I had to manually go re-register the new URL with Telegram. A pipeline that's supposed to save me time now needed me to babysit it every morning. Not exactly "fully automated."

And the more embarrassing part. the actual multi-platform posting, the part that was supposed to save the most time, never got finished. I built the capture layer. I built the dedup layer. I stopped right before the part that mattered most.

Thinking about it now, this wasn't really an automation failure. It was a sequencing mistake. I built the fun part first. Webhooks, dedup logic, the architecture diagram in my head looking clean. The boring part, a stable public URL, I left for later. Later never came.

This keeps happening in infra work and I don't think its a coincidence. The AI reformatting step, the multi-platform posting, that was the exciting 20%. Getting a reliable endpoint that survives a restart was the unglamorous 80%. Everyone wants to build the 20%. Almost nobody wants to build the 80%. But the 80% is usually what decides if the thing actually runs unattended or not.

So the pipeline still sits there. Half built. Working, technically, if I remember to re-register the URL by hand.

Anyone else have an automation project that stalled right at the boring part? curious if this is a me problem or a universal one.

#DevOps #Automation #n8n #BuildInPublic #AIAgents

Saturday, 9 March 2019

DevSecOps Pune Meetup 4



9th March 2019

This is our 4th DevSecOps meetup. More and More and More swag sponsors added to the list. New sponsors: Elastic, Sonatype, Synk along with previous sponsors i.e. Polyverse and Cloudneeti already into the list. The meetup head count was usual and exact. We have been hitting the correct and intended audience.

Qualys Pune was the venue for the meetup. This is the 2nd time we organized the meetup at Qualys. We started at 10.30 am. We had a huge list of topics this time and I was pretty sure not all of them are going to get discussed since the most voted topics were very interesting. The following topics got discussed:

  • Machine Learning for Security: This topic got discussed for a good 40 minutes although none of us was an ML engineer and only understood theoretical ML concepts. The topic was chosen more for a discussion as the person suggester of the topic just had the curiosity to see if this can be done. The topic unfolded as people discussed and understood how ML works and how is it being used in the industry. Different tools like TensorFlow, Pandas, etc got discussed. Once we had a clear picture of ML, we moved to understand what security breaches we experienced in our Ops lives in industry. Based on our experience, we framed logic as to how ML algorithm could be written by Data Science engineers by studying security auth logs and application logs. We also discussed how ELK stack could be used to prove a security attack on system and further. We agreed to the part that as an Ops person we can only best provide inputs and prove security issues in systems. An ML engineer should be the best person to provide inputs on what ML algorithms could be used to mitigate security issues.
  •  Ansible for DevSecOps CI/CD pipeline: Ansible was suggested multiple times in the past meetups as well but always went not noticed and never got discussed. In this session, we started with Ansible and went on an on for a good 1 hour. We understood how Ansible is best used in different organizations. We also discussed how a bad code in Ansible can mess up and not make any difference between olden days shell script. We discussed Idempotency feature of Ansible. We also discussed as to how Ansible is being used by some firms for Provisioning, Configuration Management and Deployment altogether. We agreed how many used Puppet for multiple jobs and later moving to a different tool was difficult for them. Hence using different tools for specific different jobs could be useful. We discussed a typical CI/CD workflow with Terraform for provisioning, Ansible for CM and Fabric/Capistrano or different language specific deployment tools for easy deployments and rollbacks. We also did a small white board presentation on how CI/CD can be used for all 3 purposes. We also discussed DR strategies, Cloud managed services like auto-scaling services etc.


  • Git for securing code : The suggester was a Developer and knew exactly how was not being used in the best manner to ensure security and highlighted some best ways like code review practices, git hooks to be used in Jenkins, linting analysis using pre-commit hooks, static code analysis with SonarQube before merge. We discussed this in details already in CI/CD pipeline above as well.
  • Burpsuite :  Burpsuite was a tool that many knew but never got a chance to use as such. The suggester of the topic had extensive experience using it and spoke about multiple possibilities and usecases that could be achieved using Burpsuite. He also highlighted on how precautions need to be  taken before using this tool for testing giving examples of one of his projects. Burpsuite indeed was very interesting for many members and we decided to have a demo session on this.
Takeaways from this session for speakers to prepare were:
  •  Session required on ML in security
  • Demo on CI/CD in DevSecOps
  • Demo on Burpsuite
Many topics that did not get discussed were:
  • Nexus scan in Jenkins pipeline
  • SonarQube for secure code analysis
  • Pentesting with Python
  • IOT Security
  • Metasploit for pentesting
  • Cloud security
  • Prowler
  • Automobile software release cycle and missing lacking devops chain
  • Maven
  • Regulations
In the end Shirish wanted to highlight the recent All Intel Chips Open To New 'Spoiler' Non-Spectre Attack

Some clicks :)














Friday, 18 January 2019

DevSecOps Pune Meetup 2

For the 2nd DevSecOps meetup, we already had our first swag sponsor. For DevOps Pune, I received swags from Docker and Ansible. Hashicorp was also planning to send a few.

With DevSecOps our 1st swag sponsor was Polyverse :) I couldn't resist posting these.


For this meetup, I changed the RSVP format to get an exact count. I was expecting to start soon at a bigger location. We couldn't risk wasting of resources. Lean coffee needs logistics to take care of and hence needs to be addressed really well. Everyone who RSVP' at the meetup page was informed to Call/SMS/WhatsApp the organizers to book a slot. So the Meetup page RSVP meant nothing.

Qualys Pune, was our venue, logistics and refreshment sponsor this time. When I 1st told them about the meetup, this is how the they arranged the seating :) :






I told them about the format and later we changed the seating to best suit the format. 

We had 12 RSVP and 10 attendees this time with just 1 last minute informed cancellation. That was a perfect number . We also made sure that the refreshment we take was a packed and long lasting one so we don't waste food. 

With 10 attendees we stared pretty much on time and this time we had a huge list to discuss and the participants were from mixed domains unlike last meetup. This time we had QAs, Support Engineers, DevOps, Consultants and Developers altogether.

The following topics got discussed:
  • Understanding PKI - Public Key Infra (How SSL Works?)
  • CIS Benchmarking
  • SOAR (Security, Orchestration, Automation and Response)
  • AWS Compliance
  • Securing serverless in Azure (Function as a Service)
  • Debian Linux and Contributing to it
  • Microservices with an example
SSL and PKI got discussed a lot since Muneeb Shaikh really explained concepts that we were unaware of that goes behind PKI formation and how public and private keys work. A 5 minutes discussion prolonged to a good long 30 minutes with inputs from everyone.

SOAR was a new process and concept that Rahul spoke about and worth reading for everyone. CIS compliance was a hit one this time too. We understood that it was topic worth presentation hence added to the DevOps Pune meetups Agenda. Later we spoke about AWS compliance and how Prowler could be used to ensure compliance in AWS. We also discussed importance of good naming conventions and Tagging in AWS. There was a chaos when we spoke about both serverless and microservices resulting to a debate topic that we discussed at the end of the meetup. The final closure was on Debian systems and how we would contribute to it.

Takeaways from this session for speakers to prepare were:
  •  PKI and SSL encryption
  • Microservices
A few topics that did not get discussed were:
  • Types of Security and importance of each
  • GRC - Governance, Risk and Compliance
  • Security Testing with Selenium
  • Achieving CI/CD with Ansible
This turned out to be a long event in spite of small number of attendees. Muneeb got Polyverse T-Shirt to keep PKI discussion happening and also actively participating in all other topics as well. Some others got stickers.

Some clicks :)





DevSecOps Pune Meetup 1

After some good success, a huge gap and some mixed learning experiences with organizing DevOps Pune meetups, I decided to start with DevSecOps Pune meetup. This was mainly since I was exploring possibilities in Information Security world. The idea started after seeing DevSecOps Seattle Meetup and the learning experience I had their simply by reading their updates. I saw regular posts on Facebook about this meetup group from my long time mentor Archis Gore. I was still confused whether to start a meetup in Pune or just stick to Seattle meetup and attend it virtually. You don't always have to be an organizer to learn.

However, Archis told me that the Seattle meetup could not be attended virtually, as the format could not support virtual attendance. This was a Lean Coffee format. Something different for me. On learning more about the format, it sounded really like a plan to start a similar meetup in Pune. Archis was here in Pune in October 2018, when I met him to understand the organizer's roles in this format. And then, and we were in or a great start. I got Rahul Khengare with me this time as a Co-organizer and started the meetup group. Cloudneeti helped us sponsor the meetup group.

The first meetup I knew would be a small one with limited attendees. I expected less than 10 attendees to show up and the RSVP count always go wrong. I remember wasting lot of food and other resources in the past due to incorrect RSVP count. I chose a location to the central Pune so that its easy to commute to everyone. Thanks to Bobby Jadhav for sponsoring the venue, i.e HauteBook's office.

We had 5 attendees in this meetup as expected. The count was not important. What was more important was whether good topics came up. With Lean Coffee we expect every participant to come up with good topics to vote for and speak about. The topics that got discussed were:

  • Docker image security and its challenges (Highest voted)
  • DevSecOps CI/CD pipeline with Kubernetes
  • Cloud Security
  • Metasploit - Kali Linux
We discussed a lot about Docker security and Snyk, Twistlock being the docker security tools were also explored further. How CIS compliance helps cloud security and the recent how engineers disable SELinux first on any system and that is a bad practice. Although just 5, the discussion went along for a huge 2 hours and it was indeed a wonderful learning experience.

We also decided later that the takeaways from these lean-coffee format will end up becoming speaker-attendee format topic for us to deep dive into important topics further. This was a great takeaway since with DevOps meetups we only spoke about what the speaker was best at, and may or may not be community learning requirement. Takeaways from this session for Speakers to prepare about was:
  • CIS Compliance
  • SELinux / Apparmour
These topics were added as Topics on DevOps Pune meetup and the hunt for the speaker started there. A few topics that did not get discussed due to lack of time were:
  • iptables
  • Ansible, Terraform and CI/CD for pod deployments on AWS
  • AWS security alternatives
  • Security compliance
  • Securing Nginx
Overall it was a wonderful learning experience. Cheers to all the attendees.

Some clicks :)



Tuesday, 26 April 2016

Configuration Management with Ansible



What is Ansible?
Opensource IT Automation tool that handles:
- Application Deployment
- Muti-tier Orchestration
- Configuration Management

Why Ansible?
- Agentless architechture
- Operates over SSH
- Configuration as data and not as code
- Python
- Self Documented/Explanatory
- Feature rich - more than 150 modules - new modules are easy to write
- Full configuration management and deployment

Installing ansible:
Python package index - pip install ansible
OS Package install - sudo apt-get install ansible
Git repo and run setup.py - git clone https://github.com/ansible/ansible.git

Ansible Modes:
Playbook mode - Execution of a series of commands in order as per written in a playbook
Non Playbook mode - Executing an ansible module command on target host

Getting Started:
- Clone the parallax repo
- the repo contains a ansible.cfg file which contains following:
------------
[defaults]
# more at http://docs.ansible.com/intro_configuration.html#the-ansible-configuration-file
# host_key_checking=False
remote_user=user
-----------
This file contains global config setting to adjust ansible

Playbooks:
They represent collection of 'plays', configuration policies, which gets applied to defined groups of hosts
A sample playbook is as follows:
-----------
- name: Install all the packages and stuff required for an EXAMPLE SERVICE
  hosts: example_servers
  user: user
  sudo: yes
  roles:
    - common
    - mongodb
    - zeromq
    - service_example
    - nodejs
#    - nginx
#    - python
#    - postgresql
#    - redis
#    - memcached
#    - deployment
------------

Anatomy of a Playbook:
A sample playbook structure is as follows:
-----------
.
├── example_servers.yml
├── group_vars
│   ├── all
│   └── example_servers
├── host_vars
│   └── example-repository
├── hosts
├── repository_server.yml
├── roles
│   ├── __template__
│   ├── common
│   ├── gridfs
│   ├── memcached
│   ├── mongodb
│   ├── nginx
│   ├── nodejs
│   ├── redis
│   ├── repository
│   ├── service_example
│   └── zeromq
└── site.yml
--------------
If we look at the tree we see a few YAML files and a few directories. There is also a filed called as 'hosts'. The hosts file is the the Ansible inventory file, it stores the hosts and their mappings to the hostgroups. The hosts file looks like this.

Simple Playbook:
--- //The three dashes on the top tells you that this is a YAML(Yet another markup language) file. Ansible playbooks are written in yaml.
- name: install and start apache //"name" keyword defines the name of the play.
  hosts: webservers //"hosts" keyword tells which hosts will the play target.
  user: root //"user" keyword tells what system user will ansible use to execute the task below

 tasks: //"tasks" under tasks you can define what module you use and you configuration
- name: install httpd
  yum: name=httpd state=present //"yum" module is being used to install httpd

- name: start httpd
  service: name=httpd state=running //"service" module is being used to start the httpd service

Ansible Architechture:
It runs as a server on your laptop. It has a inventorial host and has set of modules, there are series of playbooks that define the automation tasks. It pushes the outstanding modules modules out to the managed servers using SSH, the module runs and the resukt is returned and then the module is removed from the system. No agents are necessary for this process. This is only SSH and python are the requirements.

How does a playbook work?
When you execute a palybook, the 1st thing that happens is we gather facts. Ansible will first gather lot of useful facts from that remote system. THese can be used later on in playbooks templates and config files as variables. The tasks provided in the playbook will then be performed say 'install apache'. SO we will see that we get a changed response. which means something has been changed on the systems. if you run the same playbook again you will not get the changed response for the 2nd time, as the changes were already done in the 1st run. This is because that the expected state that we told Ansible to perform was already there and hence it did not do it for the 2nd time. This is the idempotency of Ansible.

Host Inventory: Basics
Host inventory can come from several different places, it is usually a list of hosts that you organize in a group. It can come from a file or a directory of files or from a cloud provisioning environment like EC2, Rackspace etc.

contd...

Saturday, 10 October 2015

Infrastructure Monitoring with Nagios


Image Credits : xmodulo

Server management is a real pain and the pain keeps getting worse with more and more server getting added to the infrastructure. So how do organizations sustain with huge server farms, datacenters in place? How can super admins promise an SLA of 99.99% uptime with a very low response and resolution time? Quiet obviously the answer is server monitoring solutions. It could have been so tedious for a human to monitor servers 24x7 especially when most of the systems are stable and its only once in a while some manual intervention is needed.

So what is it that needs to be really monitored? It really depends from one organization to other. For a  web development platform, response time of the page may matter a lot. The kind of traffic, 4xx's 5xx's could be a concern too. Disk Space, CPU, Memory, Swap space, particular processes and services running, DB server replication, read writes, no. of connections, query execution time and many more parameters together. Most of these checks are required by all organizations. Out of the many monitoring tools out there, one of the most used is Nagios.

Nagios is an open source software application that helps in monitoring systems, network and Infrastructure. Nagios is on top of the Linux and hence, whatever you could do with Linux could also be done with Nagios. The best part of using Nagios is the plugin based architecture and 100's and 1000's of plugins that it supports to literally allow you to monitor anything.

Nagios comes with multiple notable features that makes it distinguishing. It uses the standard protocols i.e TCP, UDP, ICMP for monitoring servers across network. You can perform multiple resource checks on any host using the NRPE addon, the checks varies from CPU, Disk RAM and many more. Not just resource checks, you could also add event handlers that perform certain actions when certain events are noticed. Checks are performed at the specified intervals, by default the interval is 5 minutes. There are 2 types of checks, Active - The one that are nags initiated. Passive - The one that are initiated externally.

Nagios consists of various objects that needs to be defined and used.

  1. Hosts : Hosts are the systems/ servers that need to be monitored in the infrastructure. Nagios also provides the facility to group set of hosts together to give a better monitoring experience. Say you can group all web servers together in a "WebServers" host group. Typically a host definition may look like : "define host{
    use                             linux-box 
    host_name                       test_host 
    alias                           CentOS 6 
    address                         5.175.142.66 
    }"
  2. Services : Services are the checks that needs to be performed. There are a wide range of service checks that can be performed on any host. Just like host group, service checks can also be grouped together. E.g you may need to check the CPU utilization of all servers together, you may group it that way. A service definition may look like : "define service{
            use                     generic-service
            host_name               test_host
            service_description     CPU Load
            check_command           check_nrpe!check_load 
            }"
  3. Contacts : Contacts are the people who need to be contacted if a notification needs to be sent for any event that occurs. You can configure contacts to send emails, samosas, or even custom messages to any service that allows messaging. Contacts can also be grouped together into a contact group. E.g there is a notification about come process getting shut down on QA server that the Admin may not necessarily be bothered about, in such a case the notification can only be sent to QA group. A contact definition will look like : "[define contact{
            name                            generic-contact
            service_notification_period     24x7
            host_notification_period        24x7
            service_notification_options    w,u,c,r,f,s
            host_notification_options       d,u,r,f,s
            service_notification_commands   notify-service-by-email
            host_notification_commands      notify-host-by-email
            register                        0   

            }
    "
  4. Commands : Commands define the exact command that will be executed on the remote hosts while executing a particular check. These are the simplest way to get particular check executed, you may also pass bash commands to perform any particular check. A command definition may look like : "define command{
            command_name check_nrpe
            command_line $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$
            }"
  5. Time Period : If a downtime is scheduled at a particular time regularly and you don't want Nagios to send you any alert at these hours, you can achieve this by adding a time period definition. This looks like : "define timeperiod{
            timeperiod_name 24x7-except-night-12-2
            alias           24x7 Except 00:00 - 02:00
            sunday          02:00-23:59
            monday          02:00-23:59
            tuesday         02:00-23:59
            wednesday       02:00-23:59
            thursday        02:00-23:59
            friday          02:00-23:59
            saturday        02:00-23:59
    }"
You can also set a monitoring schedule for a particular object if you do not want to add it to the existing service/hosts check. This allows you to explicitly look at a particular check.
Sometimes writing the definition can become a real pain using the same definition for all services and hosts can be a real pain even if you decide to copy-paste the definitions. Templates come for help here. You can define a template with all the necessary details of definition and simply use the same template everywhere in the configs. A typical template definition look like :
define host{
        name                            generic-host    
        notifications_enabled           1               
        event_handler_enabled           1               
        flap_detection_enabled          1               
        process_perf_data               1               
        retain_status_information       1               
        retain_nonstatus_information    1               
        notification_period             24x7            
        register                        0               
        }

define contact{
        name                            generic-contact         
        service_notification_period     24x7                    
        host_notification_period        24x7                    
        service_notification_options    w,u,c,r,f,s             
        host_notification_options       d,u,r,f,s               
        service_notification_commands   notify-service-by-email 
        host_notification_commands      notify-host-by-email    
        register                        0                        
        }

Monitoring in Nagios is parallel, i.e a number of hosts and service checks will go simultaneously in parallel. This could be resource consuming but this is always better than sequential monitoring as you can be sure that all your servers are doing well and don't have to wait too long for any kind of update. The add ons for Nagios are simple to make and add to the Nagios community. The configs are all split and simple to understand too. Nagios has a huge documentation and help examples for quickly getting started. 

Happy Monitoring!!

Tuesday, 18 August 2015

Software Configuration Management System

Picture credits : Paul Downey

Any application would generally consist of Web servers, Application Servers, Memcache systems, SQL and NoSQL Database servers, Load Balancers, Messaging queues, etc. Although this is pretty much enough, however as a precaution/privilege we also ensure proper redundancies so that whenever there is a failure we have a back plan in place to handle the failure. In order to keep a track of server performances we also have logging servers, Analytics servers and Monitoring servers in place. All these servers need to available again within no time in case something goes wrong(which does go wrong).

In traditional systems the admin guy managed all these by managing the wiring of the server and SSHing the servers and maintaining them throughout. There was nothing wrong with the idea except of time taken to get the process done. When something goes wrong get into that machine and spend hours finding out what went wrong and correct it my defining a good downtime. With a configuration management(CM) system in place now, we describe a state of a server and use some tool that just ensures that the server resides in that state throughout. The CM system ensures that right packages are installed, config files have correct values and permissions set and that the expected services are running on the host system and many more.

Software Deployment is another concern that a Devops person has to take care of which is at times addressed by CM tools too, although may not be considered a good practice always. Deployment is the process where the software that is written/developed by a company is built/compiled/processed and the required binaries and static files and other necessary files are copied to the server. The expected services are started as well. This is done mostly by using some scripting language and now we have some deployment specific tools that have their own advantages over scripting languages rollback being an important one. Capistrano and Fabric are famous ones.

Many a times the deployment process involves multiple remote servers. In complex environments the deployment process, the order of execution of tasks play an important role. A deployment may fail if an expected event occurs before another. E.g the database server needs to be up and running before the web server is brought up. Or in a high availability environment servers needs to be 1st taken out of the load balancer one by one before deployment and later added back to the load balancer post successful deployment. This automated arrangement, coordination and management of complex systems is called orchestration.

With a bunch of IAAS providers in the cloud market, virtualization has taken up huge pace. The evaluation of any new CM tool that comes to the IT world is largely done based on the number of cloud providers it supports. An important feature of a CM tool is provisioning. Provisioning is the process of spinning up of server for that cloud provider automatically. Many CM tools providers have plugins written to communicate with many cloud providers. Chef, Ansible, Puppet, CFEnginer, Salt have already become favorite for many out there.

I have personally used Ansible and Chef as of now. Cloud is fun indeed .. :)

Thursday, 23 April 2015

s3cmd to push large files greater than 5GB to Amazon S3

image credits:  Stefano Bertolo

Use command line utility to push s3cmd files on Amazon S3.

Install s3cmd from s3tools.org or
apt-get install yum install s3cmd OR s3cmd

Configure s3cmd by
vim ~ / .s3cfg

<Paste những info add to it and you access-key and secret-key>

[Default]
access_key = TUOWAAA99023990001
access_token = 
add_encoding_exts = 
add_headers = 
bucket_location = US 
cache_file = 
cloudfront_host = cloudfront.amazonaws.com 
default_mime_type = binary / octet-stream 
delay_updates = False 
delete_after = False 
delete_after_fetch = False 
delete_removed = False 
dry_run = False 
enable_multipart = True 
encoding = UTF-8 
encrypt = False 
EXPIRY_DATE = 
expiry_days = 
expiry_prefix = 
follow_symlinks = False 
force = False 
get_continue = False 
gpg_command = / usr / bin / gpg 
gpg_decrypt =% (gpg_command) s -d --verbose --no-use-agent --batch --yes --passphrase-fd% (passphrase_fd) s -o% (output_file) s% (input_file) s 
gpg_encrypt =% (gpg_command) s -c --verbose --no-use-agent --batch --yes --passphrase-fd% (passphrase_fd) s -o% (output_file) s% (input_file) s 
gpg_passphrase = 
guess_mime_type = True 
host_base = s3.amazonaws.com 
host_bucket =% (bucket) s.s3.amazonaws.com 
human_readable_sizes = False 
ignore_failed_copy = False 
invalidate_default_index_on_cf = False 
invalidate_default_index_root_on_cf = True 
invalidate_on_cf = False 
list_md5 = False 
log_target_prefix = 
max_delete = -1 
mime_type = 
multipart_chunk_size_mb = 15 
preserve_attrs = True 
progress_meter = True 
proxy_host = 
proxy_port = 0 
put_continue = False 
recursive = False 
recv_chunk = 4096 
reduced_redundancy = False 
restore_days = 1 
secret_key = sd / ceP_vbb # eDDDK 
send_chunk = 4096 
server_side_encryption = False 
simpledb_host = sdb.amazonaws.com 
skip_existing = False 
socket_timeout = 300 
urlencoding_mode = normal 
use_https = True 
use_mime_magic = True 
verbosity = WARNING 
website_endpoint = http: //% (bucket) s.s3-their Website% (location) s.amazonaws.com/ 
website_error = 
website_index = index.html

access_key = YOUR-ACCESS-KEY-HERE
You can see how to use s3cmd at: http://s3tools.org/usage

Here I came across a typical scenario where I could not upload files greater than 5GB. You could do this to print two Ways:


  1. Using the --multipart-chunk-size-mb flag: s3cmd put --multipart-chunk-size-mb = 4096 201412.tar.gz s3: // apache-logs / I could not do this since I Had an older version of s3cmd installed and I did not really have time to download and install những version.
  2. Splitting Into the large files using small files and then uploading it split command.
  • Original file
-rw-r - r--. 1 root root 5.4G Jan 20 06:54 201412.tar.gz
  • Split Command
split -b 3G 2014backup.tar.gz "201 412"
  • Post Split

-rw-r - r--. 1 root root 23 Apr 06:41 3.0G 201412aa
-rw-r - r--. 1 root root 23 Apr 06:43 2.4G 201412ab

  • Upload files những

201 412 * s3cmd put s3: // apache-logs /

Saved some time :)

Monday, 25 August 2014

Hadoop 1.0

some rights reserved by intelfreepress

Got opportunity to work with Hadoop with a recent project. Understanding the architecture conceptually and then learn using it is fun. I am still learning it though. This part explains Hadoop 1.0 which I believe helped me to understand 2.0 well.

Before understanding Hadoop it would make more sense if we get rid of a few jargon that would come our way.


Oozie is like a cronjob. In addition to running jobs time based, it also allows running jobs on particular statuses, like:
i. Run job B when Job A completes
ii. Run Job B when a particular file is present.
Oozie is a kind of job coordinator. When you write Oozie, you need to specify in an xml the kind of workflow you want it to follow.

Hive is a dataware housing system for hadoop.

Pig Latin is a kind of Data Analysis. Those who are not java programmers and may not be able to write complex java code can use pig to run the MapReduce job on Hadoop. Syntax is similar to erlang programming language where you could say load this file , group by etc. A simple program of 2 -3 lines which in java may take a some effort could be written easily here. The limitation could be that you may not be able to write very complex logic in Pig. If you have something simple as a log file that you just want to read data from that is separated by tabs, you could use Pig.

Mahout is a machine learning. It provides all the machine learning algorithms which are in place. Mahout just writes a wrapper around existing algos so that you can use it along with Hadoop.

HBase is hadoop database. Its a NoSQL kind of DB which is inside Hadoop and a lower layer of file system that is HDFS.

HDFS Hadoop distributed file system, will sit on top of your existing filesystem. In the native OS the file system could be ext3, ext4 etc. The HDFS sits as a pseudo filesystem on top of your existing filesystem so that you can visualize all the different filesystems on differnt nodes and clusters as one.

Flume and Scoop: Flume handles unstructured data like tweets, logs or semistructured data like xmls. Scoop handles structured data. We can configure flume to read data form apache log directory : /var/log/apache2/error.log

Hadoop has two very important parts.
1. Storage unit
2. Processing unit



Storage unit is where you store, read and write data onto i.e HDFS. This HDFS is distributed across nodes. They are natively redundant, that means it is by default redundant and you do not need to configure RAID or any other software or hardware for this. It would by default make 3 copies of each block. This number is configurable to any number of copies you need.

Hadoop has a Master Slave architecture. It has a master node and a few slave nodes that talk to the master. The master node in Hadoop is known as Name Node. All the nodes that have Data Nodes running could be slave nodes. Different instances can have different or same type of filesystems, but HDFS will be laid across all these nodes. So when you run the command "hadoop fs -ls /" it doesn't bother as to which node the file is present, It will bring files from all nodes data node1 data node2 data node3... and show up. The NameNode keeps track of all the data blocks.

Processing Unit is provided by the MapReduce framework. This can be called as the brain of Hadoop. When you supply a job to Hadoop, it will split the jobs according to the processors you have. If you have a Hadoop cluster with two nodes, each node with one processor. You can run two processes in one cluster parallely.
Locality of reference: Earlier, when you wanted to process a data you would move data close to the processing unit. This required you to 1st copy the data.  It would pull the data in the RAM and then it would process it there. This is fine when dealing with small amount of data. But in case of Hadoop you will be dealing with data in terabytes and petabytes. Here copying or moving of huge data is time consuming. In order to not invlove any data movement, now Hadoop instead moves the processing unit itself to where the data is present. This is called locality of reference.

(To be contd..)

Sunday, 27 July 2014

Mumbai Technology Meetup - DevOps Special



On July 27th 10 am a DevOps special meetup was conducted at Directiplex, Mumbai. Its very rare to see a meetup given importance as much as any other technology conference. Speakers from different organizations were present and shared their knowledge. Tremendous knowledge and experience shared free of cost. The meetup went on from 10 am (Started a little late) and went around till 5.30 pm. The agenda itself was too appealing.

No entry fees. Its a free event. Just ensure you learn and make use of that learniing :-)

======================================

11.00 am - 12.00 pm : SaltStack [incl. LXC basic]: by Rigved Rakshit - Directi

Rigved introduced to LXC its setup, its concepts and how its similar/different than Docker. SOme commands and configs. Due to lack of time he could not cover Saltstack though

=====================================

12.00 pm - 1.00 pm : Configuration Management at Rackspace by Shaunak Kashyap - Rackspace

Shaunak conducted this on Hangout while he was at a 12 hr difference. Shaunak showed how rackspace uses Ansible for getting provisioning and other CM task automated.

======================================

1.00 pm - 1.30 pm : Chef Fundamentals and DevOps by Sanju Burkule - OpexSoftware

Sanju took a brief introduction to Chef and how OpexSoftware who are partners of Chef and conduct professional Chef training with certifications. Sanju also shared his knowledge on how Chef is different from Puppet as he has used both.

======================================

1.30 pm - 2.00 pm : Lunch - Lets not talk about this. Blame the rain.

======================================

2.00 pm - 3.00 pm: Puppet [incl. preparatory VirtualBox fundamentals] by Ashish Chandra. - Reliance Jio

Ashish took introduction to Puppet some basics , how easy is it to setup a Puppet master and get going. He also shared some of his scripts that he uses to provision 500 instances in 6 - 7 minutes.

=======================================

3.00 pm - 4.00 pm: Ansible by Aditya Patawari - BrowserStack

This was the 2nd time I met Aditya, we met earlier at RootConf in Bangalore. Aditya shared introduction to Ansible and how is it better/different than Chef//Puppet.

=======================================

4.00 pm - 5.00 pm : Capistrano by Mayur Rokade - Directi

Mayur conducted a live demo of how to use Cap for deploys and a a little intro and setup for Capistrano.

=======================================

5.00 pm - 6.00 pm : Docker Fundamentals by Augustine Correa - Organizer of the event

Wednesday, 16 July 2014

RootConf 2014


I attended conference and workshop on Devops and Cloud Infrastructure - RootConf 2014 at Bangalore from 14th May to 17th May 2014.

Go Continuous Integration Tool developed by Thoughtworks

CI and Release Management tool developed by Thoughtworks. Helps to manage the build, test it and finally release. It allows you to distribute your build across many systems. So you can run your software on different platforms and make sure that it runs over all of them. You can even divide your tests and parallely run them on different systems, that way you get faster results. All the environments can be managed centrally, so you can promote builds from one environment to the next one.

Simple Steps:
1. Install Go Agent software on all the machines that are part of you system/cloud. 
2. Next configure all the agents to connect to the Go Server
3. Finally Approve every build from Management Dashboard.
4. Associate relevant resources tags for appropriate build tasks with the compatible agents (e.g resource linux, etc)

SELinux : Security Enhanced Linux

This session typically discussed about how SELinux is useful and how people do not understand its importance. Some security policies were discussed. Three important modes of SELinux; enforcing, permissive and disable. Also the hands on session discussed the behavior of these 3 modes of SELinux.

Docker : Light weight linux container

The dry-run of this session was conducted in the Docker-meetup we attended. It was a nice revision as well as some additional parts of docker were known in the session. Docker is a containerization tool that helps you make a light weight Linux container to pack, ship and run you application anywhere. It is an easy to learn tool with very few commands to be learnt and make your own Dockerfile. The containers can be shipped by making an image registry(or by using docker's image registry) by pushing the container from a dev environment and then pulling it from stage, test or prod. You are sure to see the similar environment as that of dev. So no more, "It works on my machine" reason to be heard.

Ansible : Configuration Management Tool

This is just another configuration management tool just like chef. The pros about the tools are :
1. No client server architecture
2. Very easy to install and almost no configuration needed.
3. Very simple to write playbooks, a non programmer can as well understand and write the code within no time since its just a yaml file.

Cons are:
1. Doesn't work on windows.
2. Not much support available since its relatively new.

Jenkins : Continuous Integration

Continuous Integration workshop was pretty much the way we do it traditionally. The workshop covered basics of Jenkins how a job is made and a build is tested an automated.

Conference Update 

Most of the conference talks focused on Docker LXC, Puppet/AnsibleSelf healing techniques was introduced and sounded something that we could try and introduce wherein the servers would first intelligently check and see if the problem could be solved by its own with various scripts based on the type of issue. Technique to on board a new team member without merely asking him to read documentation and rather practice hands on was discussed in brief. Tsuru is a new tool that we heard of that may help us to simplify and automate docker as well. A demo on how to testing your infrastructure with Kitchen was shown and that is exactly how we learned it also a part of it showed integration with Docker which is something we need to implement. Introduction to Microsoft Azure cloud gave us an idea of how it is different than other cloud providers. Heartbleed was discussed in brief along with few other security threats and a demo on how Heartbleed actually affected.

Tuesday, 3 June 2014

Integrating Docker with Chef


Ever since Docker was introduced to me, the first thing that came to my mind was, Docker is a replacement for Chef. Docker does almost everything that Chef did and provides me with a light weight solution. While Chef just configures the system. Well I was wrong. I read many articles, heard many speeches and came to a conclusion that, it was not Chef vs Docker, it was Chef with Docker. When they work together, you get the most powerful tool to deliver fast, light and efficiently.

I conducted a demo at Docker-Bangalore meetup #4 to show how integration with Chef and Docker works. More information on the meetup page.

What is Chef?
  • Configuration Management Tool.
  • Helps write Infrastructure as a code.
  • Users write code called ‘recipes’ to help manage and configure servers and applications.
  • Runs in client/server as well as stand-alone configuration called chef-solo.
  • Ensures each resource is properly configured and is in the desired state.
  • More on my blog Learning Chef.
What is Docker?
  • Light weight Linux container that packages an application and all its dependencies in a virtual container.
  • The container can be packed, shipped and the application can run on any Linux machine on public cloud, private cloud or bare metal.
  • Does not include OS.
  • Layers the changes made in the container just like a version control system, which allows you to reach any previous state within no time.
  • More on my blog Docker.
Why use Chef+Docker, What are the issues with Vagrant+Chef?
  • If each project is in its own VM, resource usage is prohibited. 
  • All the projects in a Single VM, management will be difficult, different versions for same software for different projects. 
  • Building and Rebuilding takes long time, partial builds or rebuilds are difficult. Unless explicitly snapshot is created at various stages. 
  • If you rely on external dependencies(which we do), full rebuilds can fail  due to one or more broken dependencies. 
  • If your stack has multiple components (web, db, cache, etc) and they are installed in 1 Vagrant VM, the resulting setup differs from production. Or you could use multiple VMs… but point # 1 holds.
Chef Pros:
  • Great at provisioning (knife bootstrap and plugins)
  • Configuring services – Writing your infrastructure as a code.
  • Testing your Infrastructure
Chef Cons:
  • Packaging applications
  • Deployments and rollbacks
  • Dynamic service delivery
Docker Pros:
  • Packaging applications
  • Deployments and rollbacks
  • Dynamic service delivery
Docker Cons:
  • Managing persistent storage
  • Complex networking
  • Monolithic services
How to get Chef and Docker work together?
The key is understanding the Developers and Operations workflow and making them work together.

Developers own:
  • Code and Libraries
  • Build and Test Automation
  • System Packages
  • Runtime Configuration
  • Release Management
  • Logs monitoring
  • Horizontal Scaling
Operations own the Platform:
  • Hosts
  • Routers
  • Monitoring
  • Logs
  • Security
  • Backing Services
Basically,
Developers take the control of the containers
&
Everything outside containers for Operations

Setting up Chef and Docker to work together:
  • Install Chef workstation with Omnibus Installer.
  • Create an account on manage.opscode.com or create your own chef-server.
  • Create a vagrant node or a cloud instance.
  • Site install docker community cookbook with site install.
  • Create your own cookbook which depends on docker.
  • Upload all cookbooks.
  • Bootstrap the node.
  • Login and verify of the node has the required images.
References:
  • Brain Flad's chef-docker cookbook
  • Gabriel Monroy's ChefConf presentation
  • StackOverflow, Google groups and Quora

Friday, 23 May 2014

Learning Chef - Part - II


some rights reserved by Matt Ray

...continued from  Learning Chef - Part - I

Consider you have to install an application. You 1st install and configure the application on a single server. It could be a developers laptop/workstation. In order to setup the application you have to perform various installation procedures i.e install packages, start services, manage database etc.
After sometime you are going to make the Application available to a larger number of public than your laptop/workstation can handle and so will need to add a database server and will make this a multi tier application. So now we have one server handling the Application request and a separate server for database. To avoid data loss we will add another App server and Database server to keep the data redundant so that data loss is avoided.
As time passes the load increases on the server with more number of people trying to access the server so we may need to add a scaling solution like a load-balancer to the server.
As in how the application usage increase and the amount of users increases we will need to add more and more app servers and add more load balancers for them.
As the database is not able to cope up with the high demand, we need to add a DB cache to the existing solution, Making the infra even more complex.

Chef is Infrastructure as a code. Using Chef you can programmatically provision and configure components. Chef ensures that each node complies to the policy. Policies are determined by the configurations included in each Node's run list. You can define the policy in your Chef configuration. Your policy states what state each resource should be in, but not how to get there. Chef-client will pull the policy from the Chef-server and enforce the policy on the Node. Policy will state what needs to installed but not how it needs to install. Chef is intelligent enough to figure that out. Chef will enforce the policy based on the resource that you specified.

Setup:

Setup a Chef Environment first by setting up Chef workstation, use the following command on Ubuntu,


curl -L https://www.opscode.com/chef/install.sh | sudo bash
 
 Login to manage.opscode.com and download the starter-kit there. Extract the chef-repo to your home directory. It should show the following contents.

cd chef-repo
ls
  .berkshelf
  .chef
  cookbooks
  roles
  .gitignore
  Berksfile
  chefignore
  README.md
  Vagrantfile

Check the .chef file present in the directory, it should show the following content.

cd .chef
  knife.rb
  org-validator.pem
  user.pem

Knife.rb will show your chef-server configuration for the workstation to be identified by the chef-server.

vim knife.rb
  # See http://docs.opscode.com/config_rb_knife.html for more information on knife configuration options

  current_dir = File.dirname(__FILE__)
  log_level                :info
  log_location             STDOUT
  node_name                "user"
  client_key               "#{current_dir}/user.pem"
  validation_client_name   "org-validator"
  validation_key           "#{current_dir}/org-validator.pem"
  chef_server_url          "https://api.opscode.com/organizations/user"
  cache_type               'BasicFile'
  cache_options( :path => "#{ENV['HOME']}/.chef/checksums" )
  cookbook_path            ["#{current_dir}/../chef-repo/cookbooks"]

Writing Recipes:

package "apache2" do
  action :install
end

template "/etc/apache2/apache.conf" do
  source "apache2.conf.erb"
  owner "root"
  group "root"
  mode "0644"
  variable(:allow_override => "All")
  notifies :reload, "service[apache2]

service "apache2" do
  action [:enable,:start]
  supports :reload => true
end

Lets consider the above recipe and understand it.
Each recipe has resources in it. The resources have :
- types -> package, template, service are the types of resources in the code
- names -> apache2, /etc/apache2/apache.conf, apache2(service) are the names of the resources in the code
- parameters ->   source "apache2.conf.erb"   owner "root"   group "root"   mode "0644"   supports :reload => true
- action to put the resource on desired state -> action :install, action [:enable,:start]
- send notification to other resources -> notifies :reload, "service[apache2]


A cookbook can be created by the command
knife cookbook create cookbookname
This will automatically create the cookbook along with all the necessary files inside it. You can delete, check the available cookbooks, delete a cookbook, upload and download a cookbook using different knife commands. You can check all the options by
knife cookbook --help

To bootstrap a new node you need to use the following command:
knife bootstrap hostname --sudo -x username -P password --ssh-port 2222 -N nodename

Creating Environments
Many a times you will want development environment and production environment to have little different configurations. e.g xdebug to be installed on dev but not on production. PayPal enabled on prod but not dev etc. Chef allows you to define different environments and also allows you to assign different nodes to a particular environment.

create a directory called environments in the chef-repo. Add the following content to a file dev.rb in it.

name "dev"
description "The dev environment"

create another file called prod.rb there and add the following content to it.

name "prod"
description "The prod environment"

Upload the environment to the chef server.
You can verify whether the environments are created in the chef server by logging in there.

Creating roles:
Roles provide a way to apply a group of recipes and attributes to all the nodes performing a particular function. e.g all the nodes which would work as db server can be assigned a db server roles and accordingly all the db server specific recipes can be applied to those nodes.

Roles can be created in the following manner. Create a roles directory in the chef-repo if it does not exist. add a file base.rb there with the following content.

name "base"
description "Base role applied to all nodes."
run_list(
  "recipe[users::sysadmins]",
  "recipe[sudo]",
  "recipe[apt]",
  "recipe[git]",
  "recipe[build-essential]",
  "recipe[vim]"
)
override_attributes(
  :authorization => {
    :sudo => {
      :users => ["ubuntu", "vagrant"],
      :passwordless => true
    }
  }
)

Here the runlist method defines a list of recipes to be applied to all the nodes that have base role. The override_attributes method tells lets us override the default attributes used by the recipes in the list. Here we are overriding attributes used by the sudo cookbook so that "vagrant" and "ubuntu" users can run sudo without entering password.

Next create another role Webserver by creating a file webserver.rb in the roles directory with the following content.

name "webserver"
description "Web server role"
all_env = [
  "role[base]",
  "recipe[php]",
  "recipe[php::module_mysql]",
  "recipe[apache2]",
  "recipe[apache2::mod_php5]",
  "recipe[apache2::mod_rewrite]",
]

run_list(all_env)

env_run_lists(
  "_default" => all_env,
  "prod" => all_env,
  #"dev" => all_env + ["recipe[php:module_xdebug]"],
  "dev" => all_env,
)

Here it shows that a method env_run_lists method in a role to define different run lists for different environments. To simplify things we create an all_env array to define the common run list for all environments, and then merge in any additional run list items unique to each environment.

Next create another role db_master.rb file with following contents:

name "db_master"
description "Master database server"

all_env = [
  "role[base]",
  "recipe[mysql::server]"
]

run_list(all_env)

env_run_lists(
  "_default" => all_env,
  "prod" => all_env,
  "dev" => all_env,
)

upload the created roles to chef-server and also verify the same. Upload roles by:
knife role from file roles/base.rb
knife role from file roles/webserver.rb
knife role from file roles/db_master.rbenv


Setting up a user account for sys-admin
Define a user account for yourself on all the nodes with admin privileges. This can be done by defining a data bag for the users cookbook, with attributes that describe the user account to create.

mkdir -p data_bags/users
vim data_bags/users/$USER.json

Add the following to the $USER.json
{
  "id": "jkg",
  "ssh_keys": "ssh-rsa ...SecretKey... roshan4074@gmail.com",
  "groups": [ "sysadmin", "dba", "devops" ],
  "uid": 2001,
  "shell": "\/bin\/bash"
}

Upload the data bag as well to the chef-server and verify
knife data bag create users
knife data bag from file users $USER.json