Friday 18 July 2014

perl oneliner

1. Decimal to binary:
perl -wl -e '$num1 = sprintf("%b",15), print $num1;'

2. Decimal to Hexa:
perl -wl -e '$num1 = sprintf("%x",15), print $num1;'

3. Decimal to Octal:
perl -wl -e '$num1 = sprintf("%o",15), print $num1;'

* Further details: perldoc -f sprintf

4. Finding duplicate line:
perl -n -e 'print if $a{$_}++;' filename (or)
perl -wnl -e 'print if $_{$_}++;' filename

5. Removing blank line:
perl -wnl -e 'print unless /^$/;' filename

6. Numbering all the lines:
perl -wnl -e 'print $_= "$. $_";' passwd


7. Print the number of lines of file(s) that match a pattern:
 perl -wnl -e '$x++ if /amit/; END {print $x+0};' file1  file2

7. example:
perl -wnl -e '$x++ if /amit/; END {print $x+0};' test
3
$cat test
amit amit
amit amit
mund mund
amit mund

8 . printing the total number of a match:
perl -waln -e '$t += /amit/ for @F; END { print $t }' test
5
$cat test
amit amit
amit amit
mund mund
amit mund

 9. printing the unix time:
perl -wl -e 'print time;'
1405679195

10. printing localtime:
perl -wl -e 'print $curTime if $curTime=localtime;'
Fri Jul 18 15:57:34 2014

perl -wl -e 'print localtime;'
41561518611451980

l$ perl -le 'print scalar gmtime'
Fri Jul 18 10:29:56 2014

$ perl -le 'print scalar localtime'
Fri Jul 18 16:00:14 2014

11. Factorial of 6:
perl -MMath::BigInt -le 'print Math::BigInt->new(6)->bfac()'
720

12. print a..z:



perl -le 'print join ",", ("a".."z");'

13. print 1..1000:
perl -le 'print join ",", ("1".."1000");'

Wednesday 16 July 2014

perl split function example

#!/usr/bin/perl
use strict;
use warnings;

#open (fh2, "file1") || die "Error opening file1: $!";
open (fh2, "/etc/passwd") || die "Error opening file1: $!";

my @array1;

while (<fh2>){
    #push  @array1, [ split ]; # push function to push the data in array1 from $_
    push  @array1, [ split/:/];
}

foreach ( @array1){

   
    print "@$_[0],";
    print "@$_[5]\n";
    print "@$_\n";        # for printing all the field.
}

Sunday 13 July 2014

perl_mysql_connect_example


#!/usr/bin/perl

use warnings;
use strict;
use DBI;

#Setp1 - creating connection object

my $dsn = 'DBI:mysql:thenewboston'; # module:db_engine:db_name
my $user = 'Username';
my $pass = 'Password';
my $host = 'localhost';

my $conn = DBI->connect($dsn,$user,$pass) || die "Error connecting" . DBI->errstr;

# step 2 - define query
my $query1 = $conn->prepare('SELECT * FROM user') || die "Error preparing query" . $conn->errstr;

# setp 3 - execute query
$query1->execute || die "Error executing query" . $conn->errstr;

# step 4 - return results
my @results;

while (@results = $query1->fetchrow_array()) {
    my $id = $results[0];
    my $name = $results[1];
    print "$id,$name\n"
}

Wednesday 9 July 2014

perl cgi examples

Follow steps for perl-cgi:

1. I have all my example code at /home/amit/Documets folder.
2. And we have to point the same to the cgi-folder.

lrwxrwxrwx 1 root root 21 Jul  9 18:22 cgi-bin -> /home/amit/Documents/

amit@laptop:/usr/lib/cgi-bin$ ls -ld perl/
drwxrwxr-x 2 amit amit 4096 Jul  9 18:51 perl/

3. All the perl scripts should have executable permission.

4. On the browser, you can try the following link as example:
http://localhost/cgi-bin/perl/hello.pl


###################
Now few perl script example:


NOTE: The first 2 lines be:

#!/usr/bin/perl

print "Content-type: text/html\n\n";


example 1:

#!/usr/bin/perl
  #
  # The traditional first program.

  # Strict and warnings are recommended.
  use strict;
  use warnings;

  # Print a message.
  print "Content-type: text/html\n\n";
  print "Hello, World!\n";



example 2:

#!/usr/bin/perl

print "Content-type: text/html\n\n";

my $str = <<"EOM";
<html>
<head>
<title>CGI Perl Example</title>
</head>
<body>
<h1>CGI Perl Example</h1>
<p>CGI Perl Example</p>
</body>
</html>
EOM

print $str



example 3:

#!/usr/bin/perl

$a = 10;
$var = <<"EOF";
This is the syntax for here document and it will continue
until it encounters a EOF in the first line.
This is case of double quote so variable value will be
interpolated. For example value of a = $a
EOF
print "$var\n";

$var = <<'EOF';
This is case of single quote so variable value will not be
interpolated. For example value of a = $a
EOF
print "$var\n";



example 4:

#!/usr/bin/perl

use strict;
use warnings;

my $text = "A useful tool in natural language processing is concordance. This allows a specific string to be displayed in its immediate context whereever it appears in a text. For example, a concordance program identifying the target string the might produce some of the following output. Notice how the occurrences of the target string line up vertically. ";

my @values = split(/ /, $text);

#print "$values[0]\n"

foreach my $val (@values) {
    print "$val\n"
}

exit 0;


Tuesday 8 July 2014

puppet manifest.pp example

Example of the manifest.pp:

$ cat puppet/manifests/default.pp
Exec { path => [ "/bin/", "/sbin/" , "/usr/bin/", "/usr/sbin/" ] }

class system-update {
  exec { 'apt-get update':
    command => 'apt-get update',
  }

  $sysPackages = [ "build-essential" ]
  package { $sysPackages:
    ensure => "installed",
    require => Exec['apt-get update'],
  }
}

class apache {
  package { "apache2":
    ensure  => present,
    require => Class["system-update"],
  }

  service { "apache2":
    ensure  => "running",
    require => Package["apache2"],
  }

}

class iotop {
  package { "iotop":
    ensure  => present,
    require => Class["system-update"],
  }
}



include apache
include system-update
include iotop

ansible playbook example

Following is a sort example of how to have a playbook and how to run the same. Note that I have already define the hosts details in the inventory file.


amit@laptop:~/ansible-playbook$ cat playbook.yaml
---
- name: install and start nginx
  hosts: vgbox
  user: vagrant
  sudo: yes

  tasks:

  - name: install subversion
    apt: pkg=subversion state=installed


  - name: install nginx
    apt: pkg=nginx state=installed update_cache=true
    notify:
      -  start nginx

  handlers:
    - name: start nginx
      service: name=nginx state=started



## To run the play-book:

$ ansible-playbook playbook.yaml

PLAY [install and start nginx] ************************************************

GATHERING FACTS ***************************************************************
ok: [vg2]
ok: [vg3]
ok: [vg4]





TASK: [install subversion] ****************************************************
changed: [vg2]
changed: [vg4]
changed: [vg3]
 

 TASK: [install nginx] *********************************************************
changed: [vg2]
changed: [vg3]
changed: [vg4]


NOTIFIED: [start nginx] *******************************************************
changed: [vg2]
changed: [vg3]
changed: [vg4]

PLAY RECAP ********************************************************************
vg2                        : ok=4    changed=3    unreachable=0    failed=0  
vg3                        : ok=4    changed=3    unreachable=0    failed=0  
vg4                        : ok=4    changed=3    unreachable=0    failed=0  



NOTE: I have the ssh key in my config file, else you can update those details at the inventory file [ default: /etc/ansible/hosts: ]

[vgbox]
vg2
vg3
vg4



## ssh config example:

Host vg2
    HostName 192.168.0.32
    Port 22
    User vagrant
    IdentityFile ~/.vagrant.d/insecure_private_key

Host vg3
    HostName 192.168.0.33
    Port 22
    User vagrant
    IdentityFile ~/.vagrant.d/insecure_private_key

Host vg4
    HostName 192.168.0.34
    Port 22
    User vagrant
    IdentityFile ~/.vagrant.d/insecure_private_key

Saturday 5 July 2014

changing nagios default home page

Following page need to update to change the nagios default home page:

File: /usr/share/nagios3/htdocs/index.php


Here are a couple of paths that you may be interested in


my update# vi /usr/share/nagios3/htdocs/index.php

<head>
<meta name="ROBOTS" content="NOINDEX, NOFOLLOW">
<title>Nagios Core</title>
<link rel="shortcut icon" href="images/favicon.ico" type="image/ico">
</head>

<?php
 // allow specifying main window URL for permalinks, etc.
#$corewindow="main.php";
$corewindow="cgi-bin/status.cgi?host=all";
if(isset($_GET['corewindow'])){

...................................
...................................
...................................

 
"Tactical Summary": cgi-bin/tac.cgi
"Map"             : cgi-bin/statusmap.cgi?host=all
"Hosts"           : cgi-bin/status.cgi?hostgroup=all&style=hostdetail
"Services"        : cgi-bin/status.cgi?host=all
"Summary"         : cgi-bin/status.cgi?hostgroup=all&style=summary
"Problems"        : cgi-bin/status.cgi?host=all&servicestatustypes=28
"Availability"    : cgi-bin/avail.cgi
"Trends"          : cgi-bin/trends.cgi
"Summary"         : cgi-bin/summary.cgi





External page:
http://code.naishe.in/2012/07/change-nagios-default-home-page.html

mysql quick learning

Primary Keys:
  - all tables should have "primary keys"
  - column that is 100% unique
  - no rows can have some primary key.

SHOW databases;

USE <db_name>

SHOW tables;

SHOW COLUMNS FROM customers;

DESC customers;

SELECT * FROM customers LIMIT 0,30;

SELECT city FROM customers;


; is must at the end of the query.
white space & multiple line is allowed.
Its a company standard to use "standard CAPS"

SELECT name,city FROM customers;

SELECT * FROM customers;

SELECT DISTINCT state FROM customers;

SELECT COUNT(state) FROM customers;

SELECT DISTINCT state FROM customers LIMIT 5;

SELECT id,name FROM customers LIMIT 5;

[ its ordering using PRIMARY KEYS by default? ]

SELECT id,name FROM customers LIMIT 5,10

[ From id 6 to 15. (total 10 rows) ]
[In mysql db record start with 0]


Fully qualify name:

SELECT customers.address FROM customers;
SELECT name FROM customers ORDER BY name;
SELECT name,address FROM customers ORDER BY id;

SELECT state,city,name FROM customers ORDER BY state,name,

SELECT name,zip FROM customers ORDER BY zip DESC;

[ASC: for ascending, but this is by default. ]

SELECT name,id FROM customers ORDER BY id DESC LIMIT 1;

SELECT name FROM customers ORDER BY name LIMIT 1;


* BASIC DATA FILTERING:

SELECT id,name FROM customers WHERE id=54;
SELECT id,name FROM customers WHERE id!=54;
SELECT id,name FROM customers WHERE id<8;
SELECT id,name FROM customers WHERE id<=8;

SELECT id,name FROM customers WHERE id BETWEEN 25 AND 30;

[ in WHERE with char,use 'SINGLE QUOTATION' mark. ]

SELECT name,state FROM customers WHERE state='CA';

SELECT name,state,city FROM customers WHERE state='ca' AND city='Hollywood';

SELECT name,state,city FROM customers WHERE city='Boston' OR state='CA';

SELECT id,name,ciry FROM customers WHERE (id=1 OR id=2) AND city='Raleigh';


[ if you have multiple AND or OR statement please use () to group them. ]


*) IN or NOT IN:

SELECT name,state FROM customers WHERE state='CA' OR state='NC' OR state='NY';

(for bunch of OR...)

SELECT name,state FROM customers WHERE state IN('CA','NC','NY') ORDER BY state;

[ its a good idea to show your record in some order. ]

SELECT name,state FROM customers WHERE state NOT IN('CA','NC','NY') ORDER BY state;

% -> wild card -> any things.

SELECT name FROM items WHERE  name LIKE 'name%';

SELECT name FROM items WHERE name LIKE '%couputer%';

[ mysql is not case sensitive. ]

-   -> only a single character.


*) Regular Expression in mysql:


we can use the same regular expression.

SELECT name FROM items WHERE name REGEXP 'abc|xyz';

SELECT name FROM items WHERE name REGEXP '[0-9]boxes';



* when you want to include your own character in your sql output:

SELECT CONCAT(city,',',state) FROM customers;

SELECT CONCAT(city,','state) AS new_address FROM customers;

SELECT name,cost,cost-1 AS sale_proce FROM items;


* MYSQL FUNCTION:

SELECT name,UPPER(name) FROM customers;
SELECT AVG(cost) FROM items;
SELECT SUM(bids) FROM items;

SELECT COUNT(name)  FROM items WHERE seller_id=6;

SELECT seller_id,COUNT(NAME) FROM items GROUP BY seller_id ORDER BY seller_id;

SELECT AVG(cost) FROM items WHERE seller_id=6;

SELECT COUNT(*) AS item_count, MAX(cost) AS max, AVG(cost) AS avg FROM items WHERE seller_id=12;


* GROUP BY:

(instead of WHERE multiple time, we can use GROUP BY )

SELECT seller_id,COUNT(*) AS item_count FROM items GROUP BY seller_id;

[ HAVING is something like WHERE in GROUP BY, so we have to use HAVING in a GROUP BY query. ]

SELECT seller_id,COUNT(*) AS item_count FROM items GROUP BY seller_id HAVING COUNT(*) >=3;

[ So, in GROUP BY use HAVING ]

SELECT seller_id,COUNT(*) AS item_count FROM items GROUP BY seller_id HAVING COUNT(*) >=3 ORDER BY items_count DESC;


*) subquery:

Lets say list those items that's cost is more then the AVG(cost);

- Mysql work like inside-out, so first () and then rest;

SELECT name,cost FROM items WHERE cost > (SELECT AVG(cost)FROM items) ORDER By cost DESC;

query(subquery)


*) mysql join tables:

SELECT cousters.id,customers.name,items.name,item.cost FROM customers,items WHERE customers.id=items.seller_id ORDER BY customers.id;

* using AS we can also give a table 'nick name' not just column.

SELECT i.seller_id,i.name,c.id FROM customers AS C, items AS i WHERE i.seller_id=c.id


* Outer joins:

Inner join: when we have to column(from different table) and we want to match them together.

[ customers.id=items.seller_id => both should have values. ]

Outer joins:

example: I want to list the customers.name  even if they are not selling or list even items, that are not getting sold by any customers now.

SELECT customers.name, items.name FROM customers LEFT OUTER JOIN  items ON customers.id=items.seller_id;

[ will list coustomers even if its not there in items table. (because customers is in the left side of LEFT OUTER JOIN)

To include all the rows from the table in LEFT.

The other one:

SELECT customers.name, items.name FROM customers RIGHT OUTER JOIN items ON customers.id=seller_id;


*) UNION:

SELECT name,cost,bids FROM items WHERE bids > 190 OR cost>1000 ORDER BY cost;


But if its become more complex:

SELECT name,cost,bids FROM items WHERE bids>190
UNION
SELECT name,cost,bids FROM items WHERE cost>1000 ORDER BY cost;


taking multiple queries & getting them into one result set. (UNION):
for every UNION column's need to be same.
By default is removes the duplicate entries.
If you don't want to remove duplicate then use UNION ALL in place of UNION


* Fully-text searching:

ALTER TABLE items ADD FULLTEXT(name);

DESC items;  -> it you see KEY column for name row we have an INDEX having MUL.


SELECT name,cost FROM items WHERE MATCH(name) AGAINST('baby');

[no regexp or wild card over here. ]

IT do the ranking too & faster.

SELECT name,cost FROM items WHERE MATCH(name) AGAINST('+baby -coat' IN BOOLEAN MODE)




################################################

*) INSERT:

INSERT INTO items(id,name,cost,seller_id,bids) VALUES('102','fish','10','1',0');

*)  Multiple Row Insert:

INSERT INTO items(id,name,cost,seller_id,bids)
VALUES
('103','apple','1','1','0'),
('104','shoe','ro','1','0'),
('105','ring','100','1','0');

INSERT INTO items(id,name,cost,seller_id,bids) SELECT id,name,cost,seller_id,bids FROM AnotherTable;


*) UPDATE:

(Best to have LIMIT too) for to be safe.

UPDATE items SET name='applecake' WHERE id=103;
UPDATE items SET name='bananna',cost='2' WHERE id=103 LIMIT 1;

UPDATE user SET Password=PASSWORD('new-password') WHERE User='root';


DELETE FROM items WHERE id=103 LIMIT 1;

*) use PRIMARY KEY in UPDATE or DELETE to be safe.





#####################################

CREATE TABLE:

CREATE TABLE user(
id int,
Username varchar(30),
Password varchar(20),
PRIMARY KEY(id)
);



*)

CREATE TABLE classics(
auther varchar(128),
title varchar(128),
category varchar(16),
year smallINT,
isbn char(13),
INDEX (auther(20)),
INDEX (title(20)),
INDEX (category(4)),
INDEX (year),
PRIMARY KEY (isbn)
) ENGINE MyISAM;


#####################################


*) ALTER/DROP/RENAME Table:

ALTER TABLE user ADD address varchar(30);

ALTER TABLE user DROP  column address;


*) TO DROP A TABLE:

 DROP TABLE user_old1;

*) Too Rename A TABLE:

RENAME TABLE user1 to users;



###########################################

*) views:

  - temporary  table;
  - don't carry any own data, its a tempory table created by other tables;

CREATE VIEW mostbids AS
SELECT id,name,bids FROM items ORDER BY bids DESC LIMIT 10;

[ top 10 bids, dynamic tables. ]
[NOTE: After AS is query and the view name over here its before AS. ]


CREATE VIEW customers AS SELECT * FROM user;

[ Over here if you delete some thing from this view table, then it will update as original table too. like sym link? ]

CREATE VIEW address AS SELECT CONCAT(city,',',state) AS fulladdress FROM users;

[ view don't take any memory. ]


#################################################

Few more topics:

trigger, cursors, store procedures.


##################################################















Thursday 3 July 2014

Vagrantfile with Puppet config example

Following is a sample Vagrantfile that will start 4 vagrant box and assigning each an public ipaddress and puppet class, where we can define what all need to deployed on there box. Over here I have provided one vagrant_box image, but if you want you can provide each host with different vagrant_box_image.



$cat Vagrantfile


VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.vm.define "vg2" do |vg2|
    vg2.vm.box = "my_vagrant_image"
    vg2.vm.hostname = "vg2"
    vg2.vm.network "public_network", :bridge => 'wlan0', :ip => "192.168.0.32"
  end

  config.vm.define "vg3" do |vg3|
    vg3.vm.box = "my_vagrant_image"
    vg3.vm.hostname = "vg3"
    vg3.vm.network "public_network", :bridge => 'wlan0', :ip => "192.168.0.33"
  end


  config.vm.define "vg4" do |vg4|
    vg4.vm.box = "my_vagrant_image.box"
    vg4.vm.hostname = "vg4"
    vg4.vm.network "public_network", :bridge => 'wlan0', :ip => "192.168.0.34"
  end

  config.vm.define "vg5" do |vg5|
    vg5.vm.box = "my_vagrant_image.box"
    vg5.vm.hostname = "vg5"
    vg5.vm.network "public_network", :bridge => 'wlan0', :ip => "192.168.0.35"
  end

  config.vm.provision :puppet do |puppet|
    puppet.manifests_path = "puppet/manifests"
    puppet.manifest_file  = "default.pp"
    puppet.options = ['--verbose']
  end



explanation of puppet class:

Note: even if we have lots of different vagrant box defined in a single Vagrantfile, we just need to have only one puppet class, that should be enough for all of the vagrant box.

    puppet.manifests_path = "puppet/manifests"

The above line says what is the path where we have the manifests file. [ Relative to the location where we have the Vagrantfile. ]

     puppet.manifest_file  = "default.pp"

The above line says which is the manifest file.


Example of the manifest.pp:

$ cat puppet/manifests/default.pp
Exec { path => [ "/bin/", "/sbin/" , "/usr/bin/", "/usr/sbin/" ] }

class system-update {
  exec { 'apt-get update':
    command => 'apt-get update',
  }

  $sysPackages = [ "build-essential" ]
  package { $sysPackages:
    ensure => "installed",
    require => Exec['apt-get update'],
  }
}

class apache {
  package { "apache2":
    ensure  => present,
    require => Class["system-update"],
  }

  service { "apache2":
    ensure  => "running",
    require => Package["apache2"],
  }

}

class iotop {
  package { "iotop":
    ensure  => present,
    require => Class["system-update"],
  }
}



include apache
include system-update
include iotop


NOTE: you have to use the include lines for deploying those package to these instance. Note: Example the iotop class also have a require => Class, pointing to the system-update class. If you don't what to have the system-update class run at your system then, you can comment these line [with # ] and comment the following include line too.


vagrant box with percona-XtraDB centos image

For testing the mysql cluster I am using the percona-XtraDB, on centos server. I choose the basic centos6.5 image for that and later I have installed the percona-XtraDB on that and did a packaging of the same, so that we all can do a quick test of the same.

Step 1:
Install virtualbox on your system. [4.1 onwards or the latest would be good. ]
 [https://www.virtualbox.org/wiki/Downloads]

Step 2:
Install the vagrant on your system.
[https://www.vagrantup.com/downloads.html ]

Step 3: 
mkdir amit-percona && cd amit-percona

Step 4:
 Download the vagrantfile from the following share location:
https://drive.google.com/file/d/0B02LZ59YLdSddDRFTDdHaWJDQXc/edit?usp=sharing

 $ vagrant box add amit-percona-XtraDB amit-percona-XtraDB


output: [ something like following: ]

==> box: Adding box 'amit-percona-XtraDB' (v0) for provider:
    box: Downloading: file:///home/amit/vagrant-boxes/amit-percona/amit-percona-XtraDB
==> box: Successfully added box 'amit-percona-XtraDB' (v0) for 'virtualbox'!

if you type: $ vagrant box list
amit-percona-XtraDB  (virtualbox, 0)
[ you will see something like this. ]

Step 5: 
 5.a: $ mv ~/.vagrant.d/boxes/amit-percona-XtraDB/0/virtualbox/include/_Vagrantfile Vagrantfile

NOTE: This above command will copy custom vagrantfile and moved to your current folder with the name Vagrantfile. [ instead of doing vagrant init ]

 5.b: cat ~/.vagrant.d/boxes/amit-percona-XtraDB/0/virtualbox/include/ssh_config >> ~/.ssh/config

NOTE: This will add my ssh_config to your .ssh/config file.

Step 6:
 $ vagrant up

NOTE: it will start 3 vagrant instance as name cenos[2-4]

Step 7:
 $ vagrant global-status
[ You can see your box information ]

Step 8:
To login: ssh centos2
               ssh centos3
               ssh centos4

[this will work out-of-box because, we have added the ssh/config already, with a private key that comes with vagrant.

or you can do:
ssh vagrant@10.0.10.2 [ password: vagrant ]


NOTE:$ rpm -qa | grep -i percona
percona-release-0.0-1.x86_64
Percona-XtraDB-Cluster-galera-2-2.10-1.188.rhel6.x86_64
Percona-XtraDB-Cluster-server-55-5.5.37-25.10.756.el6.x86_64
Percona-XtraDB-Cluster-client-55-5.5.37-25.10.756.el6.x86_64
Percona-Server-shared-compat-5.1.68-rel14.6.551.rhel6.x86_64
percona-xtrabackup-2.2.3-4982.el6.x86_64


## Enjoy the 3 running vagrant instance that you can play your mysql cluster.






###############################################
###############################################

No need to follow the following section, if you are not interested on how I did this:

################# How I did this ####################

If you are still interested how I did all this then please follow the following notes:

Step 1:
Install virtualbox on your system. [4.1 onwards, the latest would be good. ]

Step 2:
Install the vagrant on your system.

Step 3:
$ vagrant box add centos https://github.com/2creatives/vagrant-centos/releases/download/v6.5.3/centos65-x86_64-20140116.box

  - This will download the base centos image. [ around 250MB ]
 - NOTE: Will update this blog, when I can share my vagrant box. [ that is with percona-XtraDB cluster for mysql. ]


Step 4:
$ vagrant init centos

 - This will create Vagrantfile at your present directory.

Step 5:

Over write your Vagrantfile with the following entry:

VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.define "centos2" do |centos2|
    centos2.vm.box = "centos"
    centos2.vm.network :private_network, ip: "10.0.10.2"
  end

- Because this will give you a private_network ip of 10.0.10.2 at your system, and only from your system it can be accessable.

Step 6:
login to the vagrant system:
Option a: vagrant ssh centos2 # Need to be in the same directory where you have this Vagrantfile
or
Option b:  ssh vagrant@10.0.10.2  # password: vagrant

Step 7:
Installed the percona-XtraDB-Clustier over here:

  7a: sudo su -

  7b: # rpm -Uhv http://www.percona.com/downloads/percona-release/percona-release-0.0-1.x86_64.rpm
Retrieving http://www.percona.com/downloads/percona-release/percona-release-0.0-1.x86_64.rpm

  7c: yum -y install Percona-XtraDB-Cluster-server Percona-XtraDB-Cluster-client Percona-Server-shared-compat percona-xtrabackup

Step 8:
Once the installation complete I have update the VagrantFile to run the same instance 3 time.

VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.vm.define "centos4" do |centos4|
    centos4.vm.box = "centos"
    centos4.vm.network :private_network, ip: "10.0.10.4"
# centos4.vm.network "public_network", :bridge => 'wlan0', :ip => "192.168.0.30"
  end

  config.vm.define "centos2" do |centos2|
    centos2.vm.box = "centos"
    centos2.vm.network :private_network, ip: "10.0.10.2"
# centos4.vm.network "public_network", :bridge => 'wlan0', :ip => "192.168.0.31"
  end

  config.vm.define "centos3" do |centos3|
    centos3.vm.box = "centos"
    centos3.vm.network :private_network, ip: "10.0.10.3"
# centos4.vm.network "public_network", :bridge => 'wlan0', :ip => "192.168.0.32"
  end

end

NOTE: If you want your vagrant box need to get public_ip, you do the same using the following: [ as comment at above line ]
centos4.vm.network "public_network", :bridge => 'wlan0', :ip => "192.168.0.30"

Step 9: create a ssh_config file for you all that you can add the same at your ~/.ssh/config file

 Host centos2
    HostName 10.0.10.2
    Port 22
    User vagrant
    IdentityFile ~/.vagrant.d/insecure_private_key
Host centos3
    HostName 10.0.10.3
    Port 22
    User vagrant
    IdentityFile ~/.vagrant.d/insecure_private_key
Host centos4
    HostName 10.0.10.4
    Port 22
    User vagrant
    IdentityFile ~/.vagrant.d/insecure_private_key

Step 10: Repackage the same vagrant box, so that it can be re-used:

$ vagrant package centos2 --output amit-percona-XtraDB --vagrantfile Vagrantfile --include ssh_config
==> centos2: Exporting VM...
==> centos2: Compressing package to: /home/amit/vagrant-boxes/centos/amit-percona-XtraDB
==> centos2: Packaging additional file: ssh_config
==> centos2: Packaging additional file: Vagrantfile


Step 10: Now you can use my image:
 du -ksh amit-percona-XtraDB
365M    amit-percona-XtraDB

It having the base image where percona-XtraDB is install with the updated Vagrantfile that all the setting and with a ssh config file, that you can add to your ssh config so that you can use it.


Wednesday 2 July 2014

Vagrantfile multi-instance config exmaple

Few Vagrantfile config examples:


NOTE1:
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  # Every Vagrant virtual environment requires a box to build off of.
  config.vm.box = "my_vagrant_image"


## NOTE: You can set the private ip of your vagrant box.

  # using a specific IP.
  config.vm.network :private_network, ip: "10.0.0.2"  # 0.1 is not a good idea.


 end

NOTE2:
Running multiple instance:

https://docs.vagrantup.com/v2/multi-machine/index.html

Note: In the following example we can have two instance running at the same time.

VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  config.vm.define "web" do |web|
    web.vm.box = "my_vagrant_image"
    web.vm.network :private_network, ip: "10.0.0.2"
  end

  config.vm.define "db" do |db|
    db.vm.box = "my_vagrant_image"
    db.vm.network :private_network, ip: "10.0.0.3"
  end

  config.vm.define "vg4" do |vg4|
    vg4.vm.box = "my_vagrant_image.box"
    vg4.vm.network :private_network, ip: "10.0.0.4"
  end

end



## Note there a private key, you can use:
~/.vagrant.d/insecure_private_key

and you can use this as your config file:
following is an example:

Host vg2
    HostName 10.0.0.2  ## using 1 is not a good idea.
    Port 22
    User vagrant
    IdentityFile ~/.vagrant.d/insecure_private_key
Host vg3
    HostName 10.0.0.3
    Port 22
    User vagrant
    IdentityFile ~/.vagrant.d/insecure_private_key

### and can directly use:
ssh vg2
ssh vg3
ssh vg4

Note: For 10.0.0.1, if you do ssh it don't work nicely...as this act as router ip address.

of go to the same directory from where you have the config file "Vagrantfile" and can do the following:

vagrant ssh web
vagrant ssh db
vagrant ssh vg4

### Where the file stay for very first time:

/home/amit/.vagrant.d/boxes/hashicorp-VAGRANTSLASH-precise32/0/virtualbox

amit@laptop:~/.vagrant.d/boxes/hashicorp-VAGRANTSLASH-precise32/0/virtualbox$ ls -l
total 288344
-rw------- 1 amit amit 295237632 Jun 28 18:07 box-disk1.vmdk
-rw------- 1 amit amit     14103 Jun 28 18:07 box.ovf
-rw-rw-r-- 1 amit amit        25 Jun 28 18:07 metadata.json
-rw-r--r-- 1 amit amit       505 Jun 28 18:07 Vagrantfile