July 2020
« Mar    


WordPress Quotes

I try to learn from the past, but I plan for the future by focusing exclusively on the present. That's were the fun is.
Donald Trump
July 2020
« Mar    

Short Cuts

2012 SERVER (64)
2016 windows (9)
AIX (13)
Amazon (40)
Ansibile (19)
Apache (135)
Asterisk (2)
cassandra (2)
Centos (211)
Centos RHEL 7 (270)
centos8 (3)
chef (3)
cloud (2)
cluster (3)
Coherence (1)
DB2 (5)
DISK (25)
DNS (9)
Docker (30)
Eassy (11)
ELKS (1)
Fedora (6)
ftp (5)
GIT (3)
GOD (2)
Grub (1)
Hacking (10)
Hadoop (6)
health (2)
horoscope (23)
Hyper-V (10)
IIS (15)
JAVA (7)
JBOSS (32)
jenkins (1)
Kubernetes (7)
Ldap (5)
Linux (188)
Linux Commands (166)
Load balancer (5)
mariadb (14)
Mongodb (4)
MQ Server (24)
MYSQL (84)
Nagios (5)
NaturalOil (13)
Nginx (35)
Ngix (1)
openldap (1)
Openstack (6)
Oracle (35)
Perl (3)
Postfix (19)
Postgresql (1)
PowerShell (2)
Python (3)
qmail (36)
Redis (12)
RHCE (28)
Security on Centos (29)
SFTP (1)
Shell (64)
Solaris (58)
Sql Server 2012 (4)
squid (3)
SSH (10)
SSL (14)
Storage (1)
swap (3)
TIPS on Linux (28)
tomcat (62)
Ubuntu (1)
Uncategorized (30)
Veritas (2)
vfabric (1)
VMware (28)
Weblogic (38)
Websphere (71)
Windows (19)
Windows Software (2)
wordpress (1)

WP Cumulus Flash tag cloud by Roy Tanck requires Flash Player 9 or better.

Who's Online

0 visitors online now
0 guests, 0 bots, 0 members

Hit Counter provided by dental implants orange county

Git Fundamentals

Git Fundamentals


Topics To be Covered

  1. Installation

2. Setup

3. Creating a Project

4. Checking the status of the repository

5. Making changes

6. Staging the changes

7. Staging and committing

8. Commiting the changes

9. Changes, not files

10. History

11. Aliases

12. Getting older versions

13. Tagging versions

14. Discarding local changes (before staging)

15. Cancel Staged changes (before committing)

16. Cancelling commits

1. Installing Git

Installing on Linux

If you want to install the basic Git tools on Linux via a binary installer, you can generally do so through the basic package-management tool that comes with your distribution. If you’re on Fedora for example, you can use yum:

$ sudo yum install git-all

If you’re on a Debian-based distribution like Ubuntu, try apt-get:

$ sudo apt-get install git-all

For more options, there are instructions for installing on several different Unix flavors on the Git website, at http://git-scm.com/download/linux.

Installing on Mac

There are several ways to install Git on a Mac. The easiest is probably to install the Xcode Command Line Tools. On Mavericks (10.9) or above you can do this simply by trying to run git from the Terminal the very first time. If you don’t have it installed already, it will prompt you to install it.

If you want a more up to date version, you can also install it via a binary installer. An OSX Git installer is maintained and available for download at the Git website, at https://sourceforge.net/projects/git-osx-installer/

You can also install it as part of the GitHub for Mac install. Their GUI Git tool has an option to install command line tools as well. You can download that tool from the GitHub for Mac website, athttp://mac.github.com.

Installing on Windows

There are also a few ways to install Git on Windows. The most official build is available for download on the Git website. Just go to https://git-for-windows.github.io/

Another easy way to get Git installed is by installing GitHub for Windows. The installer includes a command line version of Git as well as the GUI. It also works well with Powershell, and sets up solid credential caching and sane CRLF settings. We’ll learn more about those things a little later, but suffice it to say they’re things you want. You can download this from the GitHub for Windows website, at http://windows.github.com

2. One time Git Environment Setup

Now that you have Git on your system, you’ll want to do a few things to customize your Git environment. You should have to do these things only once; they’ll stick around between upgrades. You can also change them at any time by running through the commands again.

Git comes with a tool called git config that lets you get and set configuration variables that control all aspects of how Git looks and operates. These variables can be stored in three different places:

$ git config?—?global user.name “Aravind G V”

$ git config?—?global user.email aravind_gv@intuit.com

$ git config?—?global core.editor “edit -w”

3. Creating a Project

Create a new repository

Create a New Folder or Do in Existing Folder if you want to add it to vcs

mkdir training
cd training
touch hello.txt

Create a repository

So you have a directory that contains one file. Run the git init in order to create a git repo from that directory.


git init


$ git init
Initialized empty Git repository in /Users/agv/git-training

This creates a new subdirectory named .git that contains all of your necessary repository files?—?a Git repository skeleton. At this point, nothing in your project is tracked yet

Add the page to the repository

Now let’s add the “Hello, World” page to the repository.


git add hello.txt
git commit -m "First Commit"

You will see …


$ git add hello.txt
$ git commit -m "First Commit"
[master (root-commit) 2fc4372] First Commit
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 hello.txt

Checking the status of the repository

Use the git status command, to check the current state of the repository.


git status


$ git status
# On branch master
nothing to commit (working directory clean)

The command checks the status and reports that there’s nothing to commit, meaning the repository stores the current state of the working directory, and there are no changes to record.

We will use the git status, to keep monitoring the states of both the working directory and the repository.

Making changes

Let’s add some thing in text file

vi hello.txt
Test status

Checking the status

Check the working directory’s status.


git status

You will see …


$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)
modified:   hello.txt
no changes added to commit (use "git add" and/or "git commit -a")

The first important aspect here is that git knows hello.txt file has been changed, but these changes are not yet committed to the repository.

Another aspect is that the status message hints about what to do next. If you want to add these changes to the repository, use git add. To undo the changes use git checkout.

6. Staging the changes

Adding changes

Now command git to stage changes. Check the status


git add hello.txt
git status

You will see …


$ git add hello.txt
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#   modified:   hello.txt

Changes to the hello.txt have been staged. This means that git knows about the change, but it is not permanent in the repository. The next commit will include the changes staged.

Should you decide not to commit the change, the status command will remind you that you can use the git reset command to unstage these changes.

Staging and committing

A staging step in git allows you to continue making changes to the working directory, and when you decide you wanna interact with version control, it allows you to record changes in small commits.

Suppose you have edited three files (a. html, b. html, and c. html). After that you need to commit all the changes so that the changes to a. html and b. html were a single commit, while the changes to c. html were not logically associated with the first two files and were done in a separate commit.

In theory you can do the following:

touch a.html b.html c.html
git add a.html
git add b.html
git commit -m "Changes for a and b"
git add c.html
git commit -m "Unrelated change to c"

Separating staging and committing, you get the chance to easily customize what goes into a commit

8. Committing the changes

Well, enough about staging. Let’s commit the staged changes to the repository.

When you previously used git commit for committing the first hello.html version to the repository, you included the -m flag that gives a comment on the command line. The commit command allows interactively editing comments for the commit. And now, let’s see how it works.

If you omit the -m flag from the command line, git will pop you into the editor of your choice from the list (in order of priority):

  • GIT_EDITOR environment variable
  • core.editor configuration setting
  • VISUAL environment variable
  • EDITOR environment variable

I have the EDITOR variable set to emacsclient (available for Linux and Mac).

Let us commit now and check the status.


git commit

You will see the following in your editor:


# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#   modified:   hello.html

On the first line, enter the comment: “Added hi tag”. Save the file and exit the editor (to do it in default editor, press ESC and then type:wq and hit Enter). You should see …


git commit
Waiting for Emacs...
[master 569aa96] Added h1 tag
 1 files changed, 1 insertions(+), 1 deletions(-)

“Waiting for Emacs…” is obtained from the emacsclient program sending the file to a running emacs program and waiting for it to be closed. The rest of the data is the standard commit messages.

02Checking the status

At the end let us check the status.


git status

You will see …


$ git status
# On branch master
nothing to commit (working directory clean)

The working directory is clean, you can continue working

Changes, not files

Understanding that git works with the changes, not the files.

Most version control systems work with files. You add the file to source control and the system tracks changes from that moment on.

Git concentrates on the changes to a file, not the file itself. A git add file command does not tell git to add the file to the repository, but to note the current state of the file for it to be commited later.

We will try to investigate the difference in this lesson.

First Change:


First Change

Add this change

Now add this change to the git staging.


git add hello.html

Second change:


Second Change

Check the current status


git status

You will see …


$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#   modified:   hello.txt
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#   modified:   hello.txt

Please note that hello.txt is listed in the status twice. The first change (the addition of default tags) is staged and ready for a commit. The second change (adding HTML headers) is unstaged. If you were making a commit right now, headers would not have been saved to the repository.

Let’s check.


Commit the staged changes (default values), then check the status one more time.


git commit -m "Added second "
git status

You will see …


$ git commit -m "Added second"
[master 8c32287] Added standard HTML page tags
 1 files changed, 3 insertions(+), 1 deletions(-)
$ git status
# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#   modified:   hello.txt
no changes added to commit (use "git add" and/or "git commit -a")

The status command suggests that hello.html has unrecorded changes, but is no longer in the buffer zone.

Adding the second change

Add the second change to the staging area, after that run the git status command.


git add .
git status

Note: The current directory (‘.’) will be our file to add. This is the most convenient way to add all the changes to the files of the current directory and its folders. But since it adds everything, it is a good idea to check the status prior to doing an add ., to make sure you don’t add any file that should not be added.

I wanted you to see the “add .” trick, and we will continue adding explicit files later on just in case.

You will see …


$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#   modified:   hello.html

The second change has been staged and is ready for a commit.

Commit the second change


git commit -m "Added second change"


To learn to view the project’s history.

Getting a list of changes made is a function of the git log command.


git log

You will see …


commit ef44671e9b7aef27027f9d2b438e366d3133102b
Author: Aravind G V <aravind_g@?—?— >
Date: Wed Apr 6 13:09:55 2016 +0530

XIADMIN windows scripts

commit 70d87e94e7937f8a6ce89d4cd6001d99abfb4e77
Author: Neelam Malik <Neelam_Malik@?—?>
Date: Wed Apr 6 11:21:54 2016 +0530

added app_stop

commit 77ac1140018714a6b26c27535c6279eff40c87e9
Author: Neelam Malik <aravind_gv@?—?>
Date: Wed Apr 6 11:21:32 2016 +0530

added app_status

commit 36fb85091deabfe3e590a101aa1a1aca1adfa8c2
Author: Neelam Malik ?@?—?.om>
Date: Wed Apr 6 11:21:04 2016 +0530

added app_start

added app_stop

commit e4be69a36c3a37203e2b539f97eb77b3f253fe99
Author: Neelam Malik <aravind_gv@?—?>
Date: Wed Apr 6 11:18:42 2016 +0530

One line history

You fully control over what the log shows. I like the single line format:


git log --pretty=oneline

You will see …


$ git log --pretty=oneline
fa3c1411aa09441695a9e645d4371e8d749da1dc Added HTML header
8c3228730ed03116815a5cc682e8105e7d981928 Added standard HTML page tags
43628f779cb333dd30d78186499f93638107f70b Added h1 tag
911e8c91caeab8d30ad16d56746cbd6eef72dc4c First Commit

Controlling the display of entries

There are many options to choose which entries appear in the log. Play around with the following parameters:

git log --pretty=oneline --max-count=2
git log --pretty=oneline --since='5 minutes ago'
git log --pretty=oneline --until='5 minutes ago'
git log --pretty=oneline --author=<your name>
git log --pretty=oneline --all

Details are provided in the git-log instruction.

Getting fancy

This is what I use to review the changes made within the last week. I will add?—?author=alex if I want to see only the changes made by me.

git log --all --pretty=format:"%h %cd %s (%an)" --since='7 days ago'

The ultimate format of the log

Over time, I found the following log format to be the most suitable.


git log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short

It looks like this:


$ git log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short
* fa3c141 2011-03-09 | Added HTML header (HEAD, master) [Alexander Shvets]
* 8c32287 2011-03-09 | Added standard HTML page tags [Alexander Shvets]
* 43628f7 2011-03-09 | Added h1 tag [Alexander Shvets]
* 911e8c9 2011-03-09 | First Commit [Alexander Shvets]

Let’s look at it in detail:

  • — pretty=”…” defines the output format.
  • %h is the abbreviated hash of the commit
  • %d commit decorations (e.g. branch heads or tags)
  • %ad is the commit date
  • %s is the comment
  • %an is the name of the author
  • — graph tells git to display the commit tree in the form of an ASCII graph layout
  • — date=short keeps the date format short and nice

So, every time you want to see a log, you’ll have to do a lot of typing. Fortunately, we will find out about the git aliases in the next lesson.

Other tools

Both gitx (for Mac) and gitk (for any platform) can help to explore log history.


Command aliases (optional)

Common aliases

For Windows users:


git config --global alias.co checkout
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.br branch
git config --global alias.hist 'log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short'
git config --global alias.type 'cat-file -t'
git config --global alias.dump 'cat-file -p'

Also, for users of Unix/Mac:

git status, git add, git commit, and git checkout are common commands so it is a good idea to have abbreviations for them.

Add the following to the .gitconfig file in your $HOME directory.


  co = checkout
  ci = commit
  st = status
  br = branch
  hist = log --pretty=format:\"%h %ad | %s%d [%an]\" --graph --date=short
  type = cat-file -t
  dump = cat-file -p

We’ve already talked about commit and status commands. In the previous lesson we covered the log command and will get to know the checkout command very soon. The most important thing to learn from this lesson is that you can type git st wherever you had to typegit status. Best of all, the git hist command will help you avoid the really long log command.

Go ahead and try using the new commands.

If your shell supports aliases, or shortcuts, you can add aliases on this level, too. I use:

alias gs='git status '
alias ga='git add '
alias gb='git branch '
alias gc='git commit'
alias gd='git diff'
alias go='git checkout '
alias gk='gitk --all&'
alias gx='gitx --all'
alias got='git '
alias get='git '

The go abbreviation for git checkout is very useful, allowing me to type:

go <branch>

to checkout a particular branch.

Also, I often mistype git as get or got so I created aliases for them too.

Getting older versions

To learn how to checkout any previous snapshot into the working directory.

Going back in history is very simple. The checkout command can copy any snapshot from the repo to the working directory.

Getting hashes for the previous versions


git hist

Note: Do not forget to define hist in your .gitconfig file? If you do not remember how, review the lesson on aliases.


$ git hist
* 7358571 2016-06-23 | Second Test (HEAD -> master) [Aravind G V]
* 2fc4372 2016-06-23 | First Commit [Aravind G V]

Check the log data and find the hash for the first commit. You will find it in the last line of the git hist data. Use the code (its first 7 chars are enough) in the command below. After that check the contents of the hello.html file.


git checkout <hash>
cat hello.txt

Note: Many commands depend on the hash values in the repository. Since my hash values will be different from yours, substitute in the appropriate hash value for your repository everytime you see <hash> or <treehash> in the command.

You will see …


$ git checkout 911e8c9
Note: checking out '911e8c9'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
  git checkout -b new_branch_name
HEAD is now at 911e8c9... First Commit
$ cat hello.txt
Hello, World

The checkout command output totally clarifies the situation. Older git versions will complain about not being on a local branch. But you don’t need to worry about that right now.

Note that the content of the hello.html file is the default content.

Returning to the latest version in the master branch


git checkout master
cat hello.txt

‘master’ is the name of the default branch. By checking out a branch by name, you go to its latest version.

Tagging versions

To learn how to tag commits for future references

Let’s call the current version of the hello program version 1 (v1).

Creating a tag of the first


git tag v1

Now, the current version of the page is referred to as v1.

Tags for previous versions

Let’s tag the version prior to the current version with the name v1-beta. First of all we will checkout the previous version. Instead of looking up the hash, we are going to use the ^ notation indicating “the parent of v1”.

If the v1^ notation causes troubles, try using v1~1, referencing the same version. This notation means “the first version prior to v1”.


git checkout v1^
cat hello.html


$ git checkout v1^
Note: checking out 'v1^'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
  git checkout -b new_branch_name
HEAD is now at 8c32287... Added standard HTML page tags
$ cat hello.html



git tag v1-beta

Check out by the tag name

Now try to checkout between the two tagged versions.


git checkout v1
git checkout v1-beta


$ git checkout v1
Previous HEAD position was 8c32287... Added standard HTML page tags
HEAD is now at fa3c141... Added HTML header
$ git checkout v1-beta
Previous HEAD position was fa3c141... Added HTML header
HEAD is now at 8c32287... Added standard HTML page tags

04Viewing tags with the tag command

You can see the available tags using the git tag command.


git tag


$ git tag

Viewing tags in logs

You can also check for tags in the log.


git hist master --all


$ git hist master --all
* fa3c141 2011-03-09 | Added HTML header (v1, master) [Alexander Shvets]
* 8c32287 2011-03-09 | Added standard HTML page tags (HEAD, v1-beta) [Alexander Shvets]
* 43628f7 2011-03-09 | Added h1 tag [Alexander Shvets]
* 911e8c9 2011-03-09 | First Commit [Alexander Shvets]

You can see tags (v1 and v1-beta) listed in the log together with the name of the branch (master). The HEAD shows the commit you checked out (currently v1-beta).

Discarding local changes (before staging)

To learn how to discard the working directory changes

Checking out the Master branch

Make sure you are on the lastest commit in the master brach before you continue.


git checkout master

Change hello.txt

It happens that you modify a file in your local working directory and sometimes wish just to discard the committed changes. Here is when the checkout command will help you.

Make changes to the hello.html file in the form of an unwanted comment.


no need of this line

Check the status

First of all, check the working directory’s status.


git status

Undoing the changes in the working directory

Use the checkout command in order to checkout the repository’s version of the hello.html file.


git checkout hello.txt
git status
cat hello.txt

Cancel Staged changes (before committing)

To learn how to undo changes that have been staged

Edit file and stage changes

Make changes to the hello.html file in the form of an unwanted comment


no need of this line

Stage the modified file.


git add hello.txt

Check the status

Check the status of unwanted changes .


git status


$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#   modified:   hello.txt

Status shows that the change has been staged and is ready to commit.

Reset the buffer zone

Fortunately, the displayed status shows us exactly what we should do to cancel staged changes.


git reset HEAD hello.txt


$ git reset HEAD hello.html
Unstaged changes after reset:
M   hello.html

The reset command resets the buffer zone to HEAD. This clears the buffer zone from the changes that we have just staged.

The reset command (default) does not change the working directory. Therefore, the working directory still contains unwanted comments. We can use the checkout command from the previous tutorial to remove unwanted changes from working directory.

Switch to commit version


git checkout hello.html
git status


$ git status
# On branch master
nothing to commit (working directory clean)

Our working directory is clean again.

Removing a commit from a branch

To learn to delete the branch’s latest commits

Revert is a powerful command of the previous section that allows you to cancel any commits to the repository. However, both original and cancelled commits are seen in the history of the branch (when using git log command).

Often after commit is already made, we realize that it was a mistake. It would be nice to have undo option command allowing deleting incorrect commit immediately. This command would prevent the appearance of unwanted commit in the git log history.

The reset command

We have already used reset command to match the buffer zone and the selected commit (HEAD commit was used in the previous lesson).

When a commit reference is given (ie, a branch, hash, or tag name), the reset command will…

  1. Overwrite the current branch so it will point to the correct commit
  2. Optionally reset the buffer zone so it will comply with the specified commit
  3. Optionally reset the working directory so it will match the specified commit

02Check our history

Let us do a quick scan of our commit history.


git hist

We see that the last two commits in this branch are “Oops” and “Revert Oops”. Let us remove them with reset command.

Mark this branch first

Let us mark the last commit with tag, so you can find it after removing commits.


git tag oops

Reset commit to previous Oops

At the history log (see above), the commit tagged «v1» is committing previous wrong commit. Let us reset the branch to that point. As the branch has a tag, we can use the tag name in the reset command (if it does not have a tag, we can use the hash value).


git reset --hard v1
git hist


$ git reset --hard v1
HEAD is now at fa3c141 Added HTML header

Our master branch is pointing at commit v1 and “Revert Oops” and “Oops” commits no longer exist in the branch. The?—?hard parameter points out that the working directory must be updated to reflect the new branch head.

Nothing is ever lost

What happens to the wrong commits? They are still in the repository. Actually, we still can refer to them. At the beginning of the lesson, we created «oops» tag for the canceled commit. Let us take a look at all commits.


git hist --all

We can see that the wrong commits haven’t gone. They are not listed in the master branch anymore but still remain in the repository. They would be still in the repository if we did not tag them, but then we could reference them only by their hash names. Unreferenced commits remain in the repository until the garbage collection software is run by system.

Reset dangers

Resets on local branches are usually harmless. The consequences of any “accident” can be reverted by using the proper commit.

Though, other users sharing the branch can be confused if the branch is shared on remote repositories.

Removing the tag

Oops tag has performed it’s function. Let us remove that tag and permit the garbage collector to delete referenced commit.


git tag -d oops
git hist --all

Changing commits


  • To learn how to modify an already existing commit

Change the page and commit

Post an author comment on the page.

git add hello.html
git commit -m "Add an author comment"

Change the previous commit

We do not want to create another commit for some update. Let us change the previous commit and add an update.

git add hello.html
git commit --amend -m "Add an author/email comment"

View history

git hist

Moving files

Now we will create the structure of our repository. Let us move the page in the lib directory


mkdir lib
git mv hello.html lib
git status

Moving files with git, we notify git about two things

  1. The hello.html file was deleted.
  2. The lib/hello.html file was created.

Both facts are staged immediately and ready for a commit. Git status command reports the file has been moved.

One more way to move files

A positive fact about git is that you don’t need to remember about version control to the moment when you need to commit code. What could happen if we were using the operating system command line instead of the git command to move files?

The following set of commands turned out to be identical to our last actions. It requires more work with same result.

We can do:

mkdir lib
mv hello.txt lib
git add lib/hello.txt
git rm hello.txt

Commit new directory

Let us commit this movement.


git commit -m "Moved hello.html to lib"

Creating a Branch


  • To learn how to create a local branch in the repository

It is time to make our hello world more expressive. Since it may take some time, it is best to move these changes into a new branch to isolate them from master branch changes.

Create a branch

Let us name our new branch «testbranch».


git checkout -b testbranch
git status

Note: git checkout -b <branch name> is the shortcuts for git branch <branch name> followed by agit checkout <branch name>.

Note that the git status command reports that you are in the testbranch branch.Make some changes and stage the changes.

Navigating Branches

Now your project has two branches:


git hist --all

Switching to the Master branch

To switch between branches simply use the git checkout command.


git checkout master
cat lib/hello.txt

Changes to master branch

To learn how to work with several branches with different (sometimes conflicting) changes.

At the time you are changing the style branch, someone decided to change the master branch. He added a README file.

Commit changes of README file in the master branch.


git checkout master
git add README
git commit -m "Added README"

View the different branches

Now we have a repository with two different branches. To view branches and their differences use log command as follows.


git hist --all

We have opportunity to see?—?graph of git hist in action. Adding the?—?graph option to git log causes the construction of a commit tree with the help of simple ASCII characters. We see both branches (style and master) and that the current branch is master HEAD. The Added index.html branch goes prior to both branches.

The?—?all flag guarantees that we see all the branches. By default, only the current branch is displayed.

Merging to a single branch

Merging brings changes from two branches into one. Let us go back to the testbranch branch and merge it with master.


git checkout style
git merge master
git hist --all

Creating and Resolving conflict

Return to the master and create conflict

Return to the master branch and make some changes:

git checkout master
vi lib/hello.txt
Test Status
Creating conflict
git add lib/hello.html
git commit -m 'Life is great!'

(Warning: make sure you’ve used single-quotes to avoid problems with bash and ! character)

View branches

git hist --all

Merge the master branch with testbranch

Let us go back to the testbranch branch and merge it with a new master branch.

git checkout testbranch
git merge master

If you open the lib/hello.html you will see conflict errors

Resolution of the conflict

You need to resolve the conflict manually. Make changes to lib/hello.html to achieve the following result.

Now that you’ve got a good handle on Git, let’s look at GitHub. I’m keen not to overwhelm you, so I’ve made an annotated screenshot of a GitHub project, so that you can quickly become familiar with the most common features. Yes, GitHub is more than simply a project repository, but that’s where you’re likely going to spend most of your time on the site.

Setup and Run Jenkins

Installing Jenkins:

Download latest or specific version you want to install from here.

For example:

$ wget https://updates.jenkins-ci.org/download/war/2.123/jenkins.war

Starting Jenkins

The easiest way to execute Jenkins is through the built in Jetty servlet container. You can execute Jenkins like this:

$ java -jar jenkins.war

Of course, you probably want to send the output of Jenkins to a log file, and if you’re on Unix, you probably want to use nohup:

$ nohup java -jar jenkins.war > $LOGFILE 2>&1 &

Accessing Jenkins

To see Jenkins, simply bring up a web browser and go to URL http://myServer:8080 where myServer is the name of the system running Jenkins.

How Remove Files completely from git repository history

It is straight forward to remove a file from the current commit or HEAD but if you want remove entirely from the repository’s history then you need to run couple of commands.

It took some trial and error for me to find something that worked for me

  • Find out the path fo the file in your repo
  • Execute Below command with file path
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch path_to_file" HEAD

It’s a time intensive task might takes good amount of time to complete. As it has to check each commit and remove. For my repo which is ~10 years old took almost 10hours with 90K commits.

  • If you want to push it to remote repo just do git push
git push -all

If you like it and want to spread this please clap it as mush as possible.

Create a HTTPS proxy for jenkins using NGINX

Create a HTTPS proxy for jenkins using NGINX

In situations where you have existing web sites on your server, you may find it useful to run Jenkins (or the servlet container that Jenkins runs in) behind Nginx, so that you can bind Jenkins to the part of a bigger website that you may have. This document discusses some of the approaches for doing this.


When a request arrives for certain URLs, Nginx becomes a proxy and further forward that request to Jenkins, then it forwards the response back to the client. A typical set up for mod_proxy would look like this:

When using SSL, you might want to use something like the below nginx config.

  • Terminate SSL connection at nginx
  • Proxy it internally to Jenkins on port 8080
  • Replace the Location Header of Jenkins with https instead of http

Note that the third point is pretty tricky. We use proxy_redirect http:// https://; that corresponds to Apaches’s ProxyPassReverse

upstream jenkins {
  server fail_timeout=0;

server {
  listen 80 default;
  server_name *.mydomain.com;
  rewrite ^ https://$server_name$request_uri? permanent;

server {
  listen 443 default ssl;
  server_name *.mydomain.com;

  ssl_certificate           /etc/ssl/certs/my.crt;
  ssl_certificate_key       /etc/ssl/private/my.key;

  ssl_session_timeout  5m;
  ssl_protocols  SSLv3 TLSv1;
  ssl_ciphers HIGH:!ADH:!MD5;
  ssl_prefer_server_ciphers on;

  # auth_basic            "Restricted";
  # auth_basic_user_file  /home/jenkins/htpasswd;

  location / {
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_redirect http:// https://;

    add_header Pragma "no-cache";

    proxy_pass http://jenkins;

ssh tunnel for RDS AWS

ssh tunnel for RDS via bastion host

Our RDS db is hosted on Amazon. Our Bastion(Jumphost) can connect to the db. Connections to the db are not allowed outside of the internet.



Run ssh tunnel locally:

This creates a tunnel from my local machine to the Bastion:

ssh -N -L 3307:my-rds-db.us-east-1.rds.amazonaws.com:3306 ec2-my-bastion-server.compute-1.amazonaws.com

This will forward port 3307 from your local desktop to the remote MySQL rds server through your Public facing bastion EC2 instance.

You can easily set up this tunnel every time you log into your remote EC2 instance and log into it with whatever name you prefer:

Add this to .ssh/config:

Host my_instance
  Hostname bastion-ip
  Localforward 3307 my-rds-db.us-east-1.rds.amazonaws.com:3306

Then, just:

ssh my_instance

Connect to db using your favorite db interface.

An example using mysql:

$ mysql -uusername -h -P 3307 -p

For more info man ssh:

-L [bind_address:]port:host:hostport
 Specifies that the given port on the local (client) host is to be forwarded to the given 
 host and port on the remote side.  This works by allocating a socket to listen to port on 
 the local side, optionally bound to the specified bind_address.  Whenever a connection is 
 made to this port, the connection is forwarded over the secure channel, and a connection 
 is made to host port hostport from the remote machine.  Port forwardings can also be 
 specified in the configuration file.  IPv6 addresses can be specified by enclosing the 
 address in square brackets.  Only the superuser can forward privileged ports.  By default, 
 the local port is bound in accordance with the GatewayPorts setting.  However, an explicit 
 bind_address may be used to bind the connection to a specific address.  The bind_address of 
 ``localhost'' indicates that the listening port be bound for local use only, while an empty 
  address or `*' indicates that the port should be available from all interfaces.

Adding SMS Notifications to Your Bash Scripts

Cost Note: The first 100 text messages / month are free. After that, you may start incurring charges.

Step 1: Create an Appropriate AWS User

Start by creating a new User or Group in AWS with the appropriate privileges. You do NOT want to use your root account in production, for security reasons. I would suggest creating a group here, and adding your user to that group, so you can easily expand privileges  if you want to do more things via AWS CLI.

  • Visit the IAM home, in the AWS console: https://console.aws.amazon.com/iam/
  • Click on “Users”, then “Add User”.
  • Enter a User name, and then check “Programmatic Access”
  • On the “Permissions” Screen, you can either assign the user to a group with these permissions, or assign directly. You need a minimum of AmazonSNSFullAccess permission here.
  • Review, then create your user.
  • Important : Write down or download the CSV for the access and secret key. You CANNOT get these again, without regenerating and changing them.


Create a new folder in your HOME directory (~/ on Linux/Mac or C:\Users\USERNAME\ on Windows) called .aws and then create a text file in that folder called credentials without any extension. Now add the following text to that file:

aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID
aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY


For a bit of extra security you can lock down the credentials file’s permissions to 600:

$ chmod 600 credentials

Now you’ll want to head over to your IAM console and in the users tab, click “Create New Users”, add a user called “sns-reminders”, make sure that “Generate an access key for each user” is checked and then click “Create”.

You should then be brought to a screen that looks like this:

Step 2: Install and configure AWS CLI

There are many ways to install the AWS CLI. If your platform supports it, I strongly suggest installing with PIP: sudo pip install awscli

If you cannot or wish not to use PIP, see the official guide here for installing AWS CLI.

To configure, first enter: aws configure This will prompt you for the following, which you should have noted from the step above.

AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: ENTER

The access key and secret key should have been generated in step 1. The region can be any of the AWS regions, but if you choose one that does not support SMS, you will have to force that region in the command in step 3.

Step 3: Test It Out!

Try the following code in terminal, to test and make sure everything works. Be sure to substitute your phone number with the placeholder.

aws sns publish --phone-number=1-555-555-5555 --message "Your Message Here"

aws sns publish --topic-arn arn:aws:sns::sms-ack --message "website is up"

If your default region does not support SMS, you can add this tag to force it to one that does: --region us-west-2 .

--message can also take a file name as an argument, with --message file://file.txt, instead of a string, and send the contents of that file.

Wrapping Up

That’s it! Feel free to add the line above to any of your bash scripts or cron jobs, to alert you when something occurs. For example, I have a weekly backup in addition to my nightly, so I have it text me when that has been completed.

oracle databases server

oracle databases server

create database TEST
GROUP 1 ‘C:\oraclexe\app\oracle\oradata\TEST\REDO01.LOG’ SIZE 50M BLOCKSIZE 512,
GROUP 2 ‘C:\oraclexe\app\oracle\oradata\TEST\REDO02.LOG’ SIZE 50M BLOCKSIZE 512
DATAFILE’C:\oraclexe\app\oracle\oradata\TEST\SYSTEM.DBF’ size 100m autoextend on
sysaux datafile ‘C:\oraclexe\app\oracle\oradata\TEST\SYSAUX.DBF’ size 100m autoextend on
undo tablespace undotbs1 datafile ‘C:\oraclexe\app\oracle\oradata\TEST\UNDOTBS1.DBF’ size 100m autoextend on

GROUP 1 (‘/u01/app/oracle/oradata/axisdevdb/Disk1/redo01_a.log’) SIZE 100M
GROUP 2 (‘/u01/app/oracle/oradata/axisdevdb/Disk1/redo02_a.log’) SIZE 100M
GROUP 3 (‘/u01/app/oracle/oradata/axisdevdb/Disk1/redo03_a.log’) SIZE 100M
DATAFILE ‘/u01/app/oracle/oradata/axisdevdb/Disk1/system01.dbf’ SIZE 325M REUSE
SYSAUX DATAFILE ‘/u01/app/oracle/oradata/axisdevdb/Disk1/sysaux01.dbf’ SIZE 325M REUSE

Log into the database server as a user belonging to ‘dba’ [unix ] or ‘ora_dba’ [windows ] group , typically ‘oracle’, or an administrator on your windos machine. You are able to log into Oracle as SYS user, and change the SYSTEM password by doing the following:

$ sqlplus “/ as sysdba”
SQL*Plus: Release – Production on Mon Apr 5 15:32:09 2004

Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.

Connected to:
Oracle9i Enterprise Edition Release – Production
With the OLAP and Oracle Data Mining options
JServer Release – Production

SQL> show user


SQL> passw system
Changing password for system
New password:
Retype new password:
Password changed
SQL> quit

Next, we need to change the password of SYS:

$ sqlplus “/ as system”
SQL*Plus: Release – Production on Mon Apr 5 15:36:45 2004

Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.

SP2-0306: Invalid option.
Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER}]
where <logon> ::= <username>[/<password>][@<connect_string>] | /
Enter user-name: system
Enter password:

Connected to:
Oracle9i Enterprise Edition Release – Production
With the OLAP and Oracle Data Mining options
JServer Release – Production

SQL> passw sys
Changing password for sys
New password:
Retype new password:
Password changed
SQL> quit
You should now be able to log on the SYS and SYSTEM users, with the passwords you just typed in.

Method 2: Creating pwd file (Tested on Windows Oracle 8.1.7)

Stop the Oracle service of the instance you want to change the passwords of.
Find the PWD###.ora file for this instance, this is usuallly located atC:\oracle\ora81\database\, where ### is the SID of your database.
rename the PWD###.ora file to PWD###.ora.bak for obvious safety reasons.
Create a new pwd file by issuing the command:
orapwd file=C:\oracle\ora81\database\PWD###.ora password=XXXXX
where ### is the SID and XXXXX is the password you would like to use for the SYS and INTERNAL accounts.
Start the Oracle service for the instance you just fixed. You should be able to get in with the SYS user and change other passwords from there.




Oracle default user and password

sqlplus /nolog
conn /as sysdba
alter user system identified by manager

OK, you can now use the Oracle database service normally. Specific instructions and points of attention are given in the next section.

Extra operation
1, modify the instance name

select instance from v$thread;


First, create a user
create user test identified by password
alter user test identified by password ;
Second, the authorization role
grant connect, resource to test;
revoke connect, resource from test;
Second, delete the user
drop user test;
drop user test cascade;
Fourth, create / authorize / delete the role
create role testRole;
grant select on class to testRole;
drop role testRole;

grant resource to nova; //
Role related

Fifth, create wm_concat function on 12C
11g2 and 12C have abandoned the wm_concat function

Create wm_concat function on 12C Oracle default user name and password cheat sheet

create user ums_dev identified by ums_dev?
grant session, connect, resource to ums_dev;
alter user ums_dev identified by ums_dev;
grant unlimited tablespace to ums_dev;
alter table table_user add (overdate TIMESTAMP(6));

View Oracle Role Users and Permissions

select user_id, username, DEFAULT_TABLESPACE, ACCOUNT_STATUS,PROFILE from dba_users;

select username,default_tablespace from user_users;

select * from user_role_privs;

select * from user_sys_privs

select * from user_tab_privs

Check the table related information

select sum(bytes)/(1024*1024) tablesize from user_segments where segment_name=’ZW_YINGYEZ’;

select index_name,index_type,table_name from user_indexes order by table_name

select * from user_ind_columns where table_name=’CB_CHAOBIAOSJ201004′

select sum(bytes)/(1024*1024) as indexsize from user_segments
where segment_name=upper(‘AS_MENUINFO’)

select * from v$version

Import and Export

exp dbserver/dbserver1234@ORCL file=/opt/dbserver.dmp owner=dbserver

imp dbserver/dbserver1234@XE file=c:\orabackup\full.dmp log=c:\orabackup\imp.log full=y


exp dbserver/dbserver1234@ORCL file=dbserver.dmp log=dbserver.log owner=ums rows=n

exp dbserver/dbserver1234 jdbc:oracle:thin:@ file=dbserver.dmp log=dbserver.log owner=ums rows=n

disable default webpage

Once it is done, you shall disable Apache’s default welcome page.

[root@rmohan.com ~]# sed -i ‘s/^/#&/g’ /etc/httpd/conf.d/welcome.conf

Also, prevent the Apache web server from displaying files within the web directory.

[root@rmohan.com ~]# sed -i “s/Options Indexes FollowSymLinks/Options FollowSymLinks/” /etc/httpd/conf/httpd.conf

After that, start and enable the Apache web server.

[root@rmohan.com ~]# systemctl start httpd.service
[root@rmohan.com ~]# systemctl enable httpd.service
Created symlink from /etc/systemd/system/multi-user.target.wants/httpd.service to /usr/lib/systemd/system/httpd.service.
Setup WebDAV

For Apache, there are three WebDAV-related modules which will be loaded by default when an Apache web server is getting started.

[root@rmohan.com ~]# httpd -M | grep dav
dav_module (shared)
dav_fs_module (shared)
dav_lock_module (shared)

Next, create a dedicated directory for WebDAV:

[root@rmohan.com ~]# mkdir /var/www/html/webdav
[root@rmohan.com ~]# chown -R apache:apache /var/www/html
[root@rmohan.com ~]# chmod -R 755 /var/www/html

For security purposes, you need to create a user account.

[root@rmohan.com ~]# htpasswd -c /etc/httpd/.htpasswd user1
New password:
Re-type new password:
Adding password for user user1

And also, you need to modify the owner and permissions in order to enhance security

[root@rmohan.com ~]# chown root:apache /etc/httpd/.htpasswd
[root@rmohan.com ~]# chmod 640 /etc/httpd/.htpasswd

Once it is done, you need to create a VirtialHost for WebDAV.

[root@rmohan.com ~]# vi /etc/httpd/conf.d/webdav.conf
DavLockDB /var/www/html/DavLock
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/webdav/
ErrorLog /var/log/httpd/error.log
CustomLog /var/log/httpd/access.log combined
Alias /webdav /var/www/html/webdav
<Directory /var/www/html/webdav>
AuthType Basic
AuthName “webdav”
AuthUserFile /etc/httpd/.htpasswd
Require valid-user

Once the VirtualHost is configured, you need to restart Apache to put your changes into effect.

[root@rmohan.com ~]# systemctl restart httpd.service

Test the functionality of the WebDAV server from a local machine. In order to take advantage of WebDAV, you need to use a qualified client. For example, you can install a program called cadaver on a CentOS 7 desktop

[root@rmohan.com ~]# yum install cadaver
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
* base: mirror.dhakacom.com
* epel: mirror2.totbb.net
* extras: mirrors.viethosting.com
* updates: centos-hn.viettelidc.com.vn
Resolving Dependencies
–> Running transaction check
—> Package cadaver.x86_64 0:0.23.3-9.el7 will be installed
–> Finished Dependency Resolution

Running transaction
Installing : cadaver-0.23.3-9.el7.x86_64 1/1
Verifying : cadaver-0.23.3-9.el7.x86_64 1/1

cadaver.x86_64 0:0.23.3-9.el7


Having cadaver installed, use the following command to access the WebDAV server.

[root@rmohan.com ~]# cadaver
Authentication required for webdav on server `′:
Username: user1

In the cadaver shell, you can upload and organize files as you wish. Here are some examples. To upload a local file

dav:/webdav/> put /root/Desktop/rmohan.com.txt
Uploading /root/Desktop/rmohan.com.txt to `/webdav/rmohan.com.txt’: succeeded.

To create a directory “dir1” on the WebDAV server

dav:/webdav/> mkdir dir

To quit the cadaver shell

dav:/webdav/> exit
Connection to `′ closed.
If you want to learn more about cadaver, you can look up the cadaver manual in the Bash shell. With this, the tutorial on setting up a WebDAV Server Using Apache on CentOS 7 comes to an end.

ansible trail

##### Steps for deployment of Ansible on CentOS 7

##### Dependency Tasks

### Install EPEL
sudo yum install epel-release

### Install pending updates
sudo yum -y update

##### Install Ansible

### Install Ansible
sudo yum -y install ansible

### Verify the Version
ansible –version


ansible all –list-hosts
ansible db –list-hosts
ansible db -m ping

connect with password authentication, it’s possible to do with “k”
ansible db -k -m command -a “uptime”

ansible db -k -m command -a “cat /etc/shadow” -b –ask-become-pass

other user’s priviledge except root, specify the option “–become-user=xxx”.
If you’d like to use another way to use priviledge except sudo (su | pbrun | pfexec | runas), specify the option “–become-method=xxx”.

ansible db -m ping
ansible db -m command -a uptime
ansible db -a “tail /var/log/dmesg”

ansible -m ping db
ansible -m ping -all
ansible -m command -a “df -h” db
ansible -m command -a “free -mt” db
ansible -m command -a “uptime” all
ansible -m command -a “arch” all
ansible -m shell -a “hostname” all
ansible -m command -a “df -h” db > /tmp/df_outpur.txt

ansible all -a “echo hello world”
ansible all -m ping
ansible db -m ping
ansible db -m setup -l node-1
ansible db -m command -a “hostname”
ansible db -m command -a “hostname” -o
ansible db -m command -a “uptime”
ansible db -m shell -a ‘echo $TERM’
ansible db -b -m yum -a “name=httpd state=present”

ansible web -b -m service -a “name=httpd state=started”
ansible web -b -m service -a “name=httpd state=stopped”

ansible web -a “/sbin/reboot” -f 10

Adhoc Commands

ansible web -a “yum update -y”
ansible app -a “yum -y install tomcat”
ansible app -a “service tomcat status”
ansible app -a “service tomcat start”
ansible app -a “yum -y install curl wget”
ansible app -a “curl web”
ansible app -a “bash -c ‘curl -k https://github.com/opstree-ansible/ansible-training/blob/master/attendees/exercise/application/sample.war > /var/lib/tomcat/webapps/sample.war'”
ansible app -a “service tomcat restart”
ansible app -a “curl node2.rmohan.com:8080/sample/”

ansible centos -m copy -a “src=test.txt
ansible centos -m copy -a “src=test.txt dest=/tmp/test.txt”
ansible centos -m yum -a “install libselinux-python”
ansible centos -m copy -a “src=test.txt dest=/tmp/test.txt”

vi playbook_sample.yml
# target hostname or group name
– hosts: web
# define tasks
# task name (any name you like)
– name: Test file
# use file module to set the file state
file: path=/tmp/test.conf state=touch owner=root group=root mode=0600

run Playbook
ansible-playbook playbook_sample.yml

ansible web1 -m command -a “ls -l /tmp/”

[root@controller test]# ansible web -m command -a “ls -l /tmp/test.conf”
node1.rmohan.com | SUCCESS | rc=0 >>
-rw——- 1 root root 0 Mar 31 20:29 /tmp/test.conf

create a Playbook which Apache httpd is installed and running.
vi playbook_sample2.yml
– hosts: web
# use priviledge (default : root)
become: yes
# the way to use priviledge
become_method: sudo
# define tasks
– name: httpd is installed
yum: name=httpd state=installed
– name: httpd is running and enabled
service: name=httpd state=started enabled=yes

ansible-playbook -v playbook_sample2.yml –ask-become-pass

ansible web -m shell -a “/bin/systemctl status httpd | head -3” -b –ask-become-pass

[root@controller test]# ansible web -m shell -a “/bin/systemctl status httpd | head -3” -b –ask-become-pass
SUDO password:
node1.rmohan.com | SUCCESS | rc=0 >>
? httpd.service – The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
Active: active (running) since Sat 2018-03-31 20:36:52 +08; 46s ago



– hosts: db
become: yes
become_method: sudo
– name: General packages are installed
yum: name={{ item }} state=installed
– vim-enhanced
– wget
– unzip
tags: General_Packages

[root@controller test]# ansible-playbook playbook_sample.yml –ask-become-pass
SUDO password:

PLAY [db] *****************************************************************************************************************************************************************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************************************************************************************************************************************************************
ok: [node3.rmohan.com]

TASK [General packages are installed] *************************************************************************************************************************************************************************************************************************************
ok: [node3.rmohan.com] => (item=[u’vim-enhanced’, u’wget’, u’unzip’])

PLAY RECAP ****************************************************************************************************************************************************************************************************************************************************************
node3.rmohan.com : ok=2 changed=0 unreachable=0 failed=0

[root@controller test]#

ansible db -m shell -a “rpm -qa | grep -E ‘vim-enhanced|wget|unzip'” –ask-become-pass

variables from “GATHERING FACTS”
vi playbook_sample3.yml

# refer to “ansible_distribution”, “ansible_distribution_version”
– hosts: target_servers
– name: Refer to Gathering Facts
command: echo “{{ ansible_distribution }} {{ ansible_distribution_version }}”
register: dist
– debug: msg=”{{ dist.stdout }}”

[root@controller test]# ansible-playbook playbook_sample3.yml

PLAY [web] ****************************************************************************************************************************************************************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************************************************************************************************************************************************************
ok: [node1.rmohan.com]

TASK [Refer to Gathering Facts] *******************************************************************************************************************************************************************************************************************************************
changed: [node1.rmohan.com]

TASK [debug] **************************************************************************************************************************************************************************************************************************************************************
ok: [node1.rmohan.com] => {
“msg”: “CentOS 7.4.1708″

PLAY RECAP ****************************************************************************************************************************************************************************************************************************************************************
node1.rmohan.com : ok=3 changed=1 unreachable=0 failed=0

vi playbook_sample4.yml
– hosts: target_servers
become: yes
become_method: sudo
– name: restart sshd
service: name=sshd state=restarted
– name: edit sshd_config
lineinfile: >
regexp=”{{ item.regexp }}”
line=”{{ item.line }}”
– { regexp: ‘^#PermitRootLogin’, line: ‘PermitRootLogin no’ }
notify: restart sshd
tags: Edit_sshd_config

ansible-playbook playbook_sample4.yml –ask-become-pass

export JAVA_HOME=/opt/java/java/
export JRE_HOME=/opt/java/java/jre
export PATH=$PATH:/opt/java/java/bin:/opt/java/java/jre/bin


two lines info my /etc/sysctl.conf

net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1

sysctl net.bridge.bridge-nf-call-iptables=1
swapoff -a
firewall-cmd –reload
modprobe br_netfilter
echo ‘1’ > /proc/sys/net/bridge/bridge-nf-call-iptables

kubeadm reset

echo ‘Environment=”KUBELET_EXTRA_ARGS=–fail-swap-on=false”‘ >> /etc/systemd/system/kubelet.service.d/10-kubeadm.conf

systemctl daemon-reload
systemctl restart kubelet

kubeadm init

[root@k8s-master ~]# mkdir -p $HOME/.kube
[root@k8s-master ~]# cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
[root@k8s-master ~]# chown $(id -u):$(id -g) $HOME/.kube/config

Step 1: Disable SELinux & setup firewall rules

Login to your kubernetes master node and set the hostname and disable selinux using following commands

~]# hostnamectl set-hostname ‘k8s-master’
~]# exec bash
~]# setenforce 0
~]# sed -i –follow-symlinks ‘s/SELINUX=enforcing/SELINUX=disabled/g’ /etc/sysconfig/selinux

Set the following firewall rules.

[root@k8s-master ~]# firewall-cmd –permanent –add-port=6443/tcp
[root@k8s-master ~]# firewall-cmd –permanent –add-port=2379-2380/tcp
[root@k8s-master ~]# firewall-cmd –permanent –add-port=10250/tcp
[root@k8s-master ~]# firewall-cmd –permanent –add-port=10251/tcp
[root@k8s-master ~]# firewall-cmd –permanent –add-port=10252/tcp
[root@k8s-master ~]# firewall-cmd –permanent –add-port=10255/tcp
[root@k8s-master ~]# firewall-cmd –reload
[root@k8s-master ~]# modprobe br_netfilter
[root@k8s-master ~]# echo ‘1’ > /proc/sys/net/bridge/bridge-nf-call-iptables

Note: In case you don’t have your own dns server then update /etc/hosts file on master and worker nodes k8s-master worker-node1 worker-node2

Step 2: Configure Kubernetes Repository

Kubernetes packages are not available in the default CentOS 7 & RHEL 7 repositories, Use below command to configure its package repositories.

[root@k8s-master ~]# cat <<EOF > /etc/yum.repos.d/kubernetes.repo
> [kubernetes]
> name=Kubernetes
> baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
> enabled=1
> gpgcheck=1
> repo_gpgcheck=1
> gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg
> https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
> EOF [root@k8s-master ~]#

Step 3: Install Kubeadm and Docker

Once the package repositories are configured, run the beneath command to install kubeadm and docker packages.

[root@k8s-master ~]# yum install kubeadm docker -y

Start and enable kubectl and docker service

[root@k8s-master ~]# systemctl restart docker && systemctl enable docker
[root@k8s-master ~]# systemctl restart kubelet && systemctl enable kubelet

Step 4: Initialize Kubernetes Master with ‘kubeadm init’

Run the beneath command to initialize and setup kubernetes master.

[root@k8s-master ~]# kubeadm init

[root@k8s-master ~]# mkdir -p $HOME/.kube
[root@k8s-master ~]# cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
[root@k8s-master ~]# chown $(id -u):$(id -g) $HOME/.kube/config

Step 5: Deploy pod network to the cluster

Try to run below commands to get status of cluster and pods.


To make the cluster status ready and kube-dns status running, deploy the pod network so that containers of different host communicated each other. POD network is the overlay network between the worker nodes.

Run the beneath command to deploy network.

[root@k8s-master ~]# export kubever=$(kubectl version | base64 | tr -d ‘\n’)
[root@k8s-master ~]# kubectl apply -f “https://cloud.weave.works/k8s/net?k8s-version=$kubever”
serviceaccount “weave-net” created
clusterrole “weave-net” created
clusterrolebinding “weave-net” created
daemonset “weave-net” created
[root@k8s-master ~]#

Now run the following commands to verify the status

[root@k8s-master ~]# kubectl get nodes
k8s-master Ready 1h v1.7.5
[root@k8s-master ~]# kubectl get pods –all-namespaces
kube-system etcd-k8s-master 1/1 Running 0 57m
kube-system kube-apiserver-k8s-master 1/1 Running 0 57m
kube-system kube-controller-manager-k8s-master 1/1 Running 0 57m
kube-system kube-dns-2425271678-044ww 3/3 Running 0 1h
kube-system kube-proxy-9h259 1/1 Running 0 1h
kube-system kube-scheduler-k8s-master 1/1 Running 0 57m
kube-system weave-net-hdjzd 2/2 Running 0 7m
[root@k8s-master ~]#

Perform the following steps on each worker node
Step 1: Disable SELinux & configure firewall rules on both the nodes

Before disabling SELinux set the hostname on the both nodes as ‘worker-node1’ and ‘worker-node2’ respectively

~]# setenforce 0
~]# sed -i –follow-symlinks ‘s/SELINUX=enforcing/SELINUX=disabled/g’ /etc/sysconfig/selinux
~]# firewall-cmd –permanent –add-port=10250/tcp
~]# firewall-cmd –permanent –add-port=10255/tcp
~]# firewall-cmd –permanent –add-port=30000-32767/tcp
~]# firewall-cmd –permanent –add-port=6783/tcp
~]# firewall-cmd –reload
~]# echo ‘1’ > /proc/sys/net/bridge/bridge-nf-call-iptables

Step 2: Configure Kubernetes Repositories on both worker nodes

~]# cat <<EOF > /etc/yum.repos.d/kubernetes.repo

Step 3: Install kubeadm and docker package on both nodes

[root@worker-node1 ~]# yum install kubeadm docker -y
[root@worker-node2 ~]# yum install kubeadm docker -y

Start and enable docker service

[root@worker-node1 ~]# systemctl restart docker && systemctl enable docker
[root@worker-node2 ~]# systemctl restart docker && systemctl enable docker

Step 4: Now Join worker nodes to master node

To join worker nodes to Master node, a token is required. Whenever kubernetes master initialized , then in the output we get command and token. Copy that command and run on both nodes.

[root@worker-node1 ~]# kubeadm join –token a3bd48.1bc42347c3b35851

[root@worker-node2 ~]# kubeadm join –token a3bd48.1bc42347c3b35851

yum update -y
modprobe br_netfilter
sysctl net.bridge.bridge-nf-call-iptables=1
sysctl net.bridge.bridge-nf-call-ip6tables=1

cat <<EOF > /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
sysctl –system

swapoff -a

yum install -y yum-utils device-mapper-persistent-data lvm2

yum-config-manager –add-repo https://download.docker.com/linux/centos/docker-ce.repo

yum makecache fast

cat <<EOF > /etc/yum.repos.d/kubernetes.repo