0% found this document useful (0 votes)
64 views183 pages

Devops Lab Exercises Preeti Dovala

This document provides a comprehensive step-by-step guide for setting up Git on Windows, Mac, and Amazon Linux 2, along with instructions for creating and managing sample projects. It covers essential Git commands, including initializing repositories, staging and committing changes, and using `.gitignore`. Additionally, it explains the differences between untracked and unstaged files, and includes practice exercises to reinforce learning.

Uploaded by

60millionbabies
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views183 pages

Devops Lab Exercises Preeti Dovala

This document provides a comprehensive step-by-step guide for setting up Git on Windows, Mac, and Amazon Linux 2, along with instructions for creating and managing sample projects. It covers essential Git commands, including initializing repositories, staging and committing changes, and using `.gitignore`. Additionally, it explains the differences between untracked and unstaged files, and includes practice exercises to reinforce learning.

Uploaded by

60millionbabies
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 183

Previous

GIT - Day-1
Sep-by-step guide to setting up Git on Windows, Mac, and an Amazon Linux 2
EC2 instance, along with a sample project to practice with.

### Step 1: Install Git

#### On Windows
1. Download Git for Windows: Go to the [Git for Windows download page]
(https://git-scm.com/download/win) and download the installer.
2. Run the installer: Follow the installation prompts, accepting the default
settings. This will also install Git Bash, a command-line interface for Git.

#### On Mac
1. Install Xcode Command Line Tools: Open the Terminal and run:

xcode-select --install

2. Install Git using Homebrew (if you have Homebrew installed):

brew install git

#### On Amazon Linux 2 EC2 Instance


1. Connect to your EC2 instance using SSH.
2. Install Git by running:

sudo yum update -y


sudo yum install git -y
### Step 2: Configure Git

Configure Git with your user name and email address. This is important for
tracking changes.

git config --global user.name "Your Name"


git config --global user.email "[email protected]"

### Step 3: Create a Sample Project

#### Step 3.1: Initialize a Local Repository

1. Create a new directory for your project:

mkdir sample-git-project
cd sample-git-project

2. Initialize a Git repository:

git init
#### Step 3.2: Create a README File

1. Create a README file:

echo "# Sample Git Project" > README.md

2. Add the README file to the staging area:


git status
git add README.md

3. Commit the README file:

git status
git commit -m "Initial commit with README"
git status

### Summary

This guide walks you through installing Git on various operating systems,
configuring it, creating a sample project. Practicing these steps will help you get
comfortable with the basic Git workflow.

step-by-step guide to creating a new sample project to practice various Git


commands. I will explain each command as we go along.

### Step 1: Initialize a New Git Repository

1. Create a new directory for your project and navigate into it:
mkdir my-git-practice
cd my-git-practice

2. Initialize a Git repository:

git init

*Explanation*: `git init` initializes a new Git repository. It creates a hidden


`.git` directory that stores all the information needed for version control.

3. List all files, including hidden ones:

ls -la

*Explanation*: `ls -la` lists all files and directories, including hidden ones
(those starting with a dot), in the current directory. You'll see the `.git` directory
here, indicating that this is a Git repository.

### Step 2: Create and Add Files

1. Create a new file using `touch`:

touch README.md

*Explanation*: `touch` creates an empty file. Here, `README.md` is created.

2. Add content to the file using `echo`:

echo "# My Git Practice Project" > README.md

*Explanation*: `echo` outputs the string to the terminal. Using `>` redirects
the output to the file `README.md`, overwriting its content if it already exists.
3. Check the status of your repository:

git status

*Explanation*: `git status` displays the state of the working directory and the
staging area. It shows which changes have been staged, which haven't, and
which files aren't being tracked by Git.

4. Add the file to the staging area:

git add README.md

*Explanation*: `git add` adds changes in the working directory to the staging
area, preparing them to be included in the next commit.

### Step 3: Commit Changes

1. Commit the staged changes:

git commit -m "Initial commit with README"

*Explanation*: `git commit` captures a snapshot of the project's currently


staged changes. The `-m` option allows you to add a commit message inline.

### Step 4: View Information About Your Repository

1. List files tracked by Git:

git ls-files

*Explanation*: `git ls-files` lists all the files that are being tracked by Git.
2. View the commit history:

git log

*Explanation*: `git log` shows the commit history for the repository. By
default, it displays the commits in reverse chronological order.

3. View a simplified commit history:

git log --oneline

*Explanation*: `git log --oneline` shows a simplified view of the commit


history, displaying each commit on a single line. This includes the commit hash
and the commit message.

Explaining the difference between "untracked" and "unstaged" files in Git,


followed by a sample project to practice with.

### Untracked vs. Unstaged

- Untracked Files: These are files in your working directory that are not being
tracked by Git. They are new files that Git has not been told to keep track of yet.
When you create a new file in a Git repository, it starts as untracked.

- Unstaged Files: These are files that are tracked by Git and have been modified
but have not yet been added to the staging area using `git add`. Git knows about
these files and their changes, but they are not marked for inclusion in the next
commit.

### Sample Project for Practice


#### Step 1: Set Up the Project

1. Create a new directory for your project and navigate into it:

mkdir git-practice
cd git-practice

2. Initialize a Git repository:

git init

#### Step 2: Create and Work with Files

1. Create a new untracked file:

echo "Hello, World!" > hello.txt

At this point, `hello.txt` is untracked.

2. Check the status of your repository:

git status

You will see `hello.txt` listed under "Untracked files".

3. Stage the file:

git add hello.txt

4. Commit the staged file:

git commit -m "Add hello.txt"


#### Step 3: Modify and Track Changes

1. Modify the file:

echo "Hello, Git!" >> hello.txt

2. Check the status again:

git status

You will see `hello.txt` listed under "Changes not staged for commit". This
means the file is unstaged.

3. Create another untracked file:

echo "This is a new file." > newfile.txt

4. Check the status once more:

git status

You will see `hello.txt` under "Changes not staged for commit" and
`newfile.txt` under "Untracked files".

#### Step 4: Practice Commands

1. Stage the changes to `hello.txt`:


git add hello.txt

2. Check the status:

git status

Now `hello.txt` should be listed under "Changes to be committed", and


`newfile.txt` remains untracked.

3. Commit the staged changes:

git commit -m "Update hello.txt"

4. Stage and commit the new file:

git add newfile.txt


git commit -m "Add newfile.txt"

### Summary of Commands

- `git init`: Initializes a new Git repository.


- `git status`: Displays the state of the working directory and the staging area.
- `git add <file>`: Adds changes to the staging area.
- `git commit -m "<message>"`: Records changes to the repository.
- `echo "text" > file.txt`: Creates a file with the specified text.
- `echo "text" >> file.txt`: Appends text to a file.

### Practice Summary

1. Create a new file (`hello.txt`), which will be untracked.


2. Stage and commit `hello.txt`.
3. Modify `hello.txt`, making it unstaged.
4. Create another new file (`newfile.txt`), which will be untracked.
5. Stage and commit the changes to `hello.txt`.
6. Stage and commit `newfile.txt`.

By practicing these steps, you’ll get a better understanding of the difference


between untracked and unstaged files and become more comfortable with basic
Git operations.
Previous

DevOps Training
WhatsApp *91 8886740600*

Preethi Dovala

akshay alone

Home


Syllabus

Live Training


Video Tutorials

 Policies

Blog


Home

GIT - Day-2
QUIZ

sample project to practice using `git diff` and `git diff --staged` commands.

### Step 1: Set Up the Project

1. Create a new directory for your project and navigate into it:
mkdir git-diff-practice
cd git-diff-practice
2. Initialize a Git repository:
git init
### Step 2: Create and Commit Initial Files

1. Create a new file:


echo "Initial content" > file1.txt
2. Stage the file:
git add file1.txt
3. Commit the file:
git commit -m "Initial commit with file1.txt"
### Step 3: Modify the File and Use `git diff`
1. Modify `file1.txt`:
echo "Additional content" >> file1.txt
2. View the differences between the working directory and the last commit:
git diff
*Explanation*: `git diff` shows the changes between the working directory and
the last commit. This will display the changes made to `file1.txt`.

### Step 4: Stage the Changes and Use `git diff --staged`

1. Stage the modified file:


git add file1.txt

2. View the differences between the staging area and the last commit:
git diff --staged
*Explanation*: `git diff --staged` shows the changes between the staging area
and the last commit. This will display the changes that have been staged for the
next commit.

### Practice Summary

1. Create a new file (`file1.txt`) and add initial content.


2. Initialize a Git repository and make the first commit.
3. Modify the file (`file1.txt`) and view the differences using `git diff`.
4. Stage the changes to `file1.txt` and view the differences using `git diff --
staged`.
### Explanation of Commands

- `git init`: Initializes a new Git repository.


- `echo "text" > file.txt`: Creates a file with the specified text.
- `git add <file>`: Adds changes to the staging area.
- `git commit -m "<message>"`: Records changes to the repository.
- `echo "text" >> file.txt`: Appends text to a file.
- `git diff`: Shows changes between the working directory and the last commit.
- `git diff --staged`: Shows changes between the staging area and the last
commit.

By following these steps, you'll gain hands-on experience with `git diff` and `git
diff --staged`, helping you understand how to track and compare changes in
your Git repository.

sample project to practice using `git rm`, and `git rm --cached` commands.

### Step 1: Set Up the Project

1. Create a new directory for your project and navigate into it:
mkdir git-rm-practice
cd git-rm-practice
2. Initialize a Git repository:
git init
### Step 2: Create and Commit Initial Files
1. Create a couple of new files:
echo "File 1 content" > file1.txt
echo "File 2 content" > file2.txt
2. Stage and commit the files:
git add file1.txt file2.txt
git commit -m "Initial commit with file1.txt and file2.txt"
### Step 3: Practice Using `git rm`

1. Remove `file1.txt` from both the working directory and the staging area:
git rm file1.txt
2. Check the status to see that `file1.txt` is staged for removal:
git status
3. Commit the change:
git commit -m "Remove file1.txt"
4. List the files tracked by Git:
git ls-files
*Explanation*: `git ls-files` lists all the files that are being tracked by Git.

### Step 5: Practice Using `git rm --cached`

1. Create and add a new file:


echo "File 3 content" > file3.txt
git add file3.txt

2. Check the status:


git status
3. Remove `file3.txt` from the staging area but keep it in the working directory:
git rm --cached file3.txt
4. Check the status again to see `file3.txt` is no longer staged but is still in the
working directory:
git status
### Practice Summary

1. Create and commit initial files (`file1.txt` and `file2.txt`).


2. Remove a file (`file1.txt`) using `git rm` and commit the change.
3. List tracked files using `git ls-files`.
4. Add a new file (`file3.txt`), then remove it from the staging area using `git rm
--cached`.

### Explanation of Commands

- `git init`: Initializes a new Git repository.


- `echo "text" > file.txt`: Creates a file with the specified text.
- `git add <file>`: Adds changes to the staging area.
- `git commit -m "<message>"`: Records changes to the repository.
- `git rm <file>`: Removes a file from both the working directory and the staging
area.
- `git ls-files`: Lists all files tracked by Git.
- `git rm --cached <file>`: Removes a file from the staging area but keeps it in the
working directory.

By following these steps, you'll gain hands-on experience with `git rm`, `git ls-
files`, and `git rm --cached`, helping you understand how to manage files in your
Git repository.
sample project to practice using the `.gitignore` file in Git.

### Step 1: Set Up the Project

1. Create a new directory for your project and navigate into it:
mkdir git-ignore-practice
cd git-ignore-practice
2. Initialize a Git repository:
git init
### Step 2: Create and Commit Initial Files

1. Create some files and directories:


echo "Initial content" > file1.txt
echo "Some content" > file2.log
mkdir temp
echo "Temporary data" > temp/tempfile.txt
2. Stage and commit the files:
git add .
git commit -m "Initial commit with file1.txt, file2.log, and temp directory"
### Step 3: Create a `.gitignore` File

1. Create a `.gitignore` file:


touch .gitignore
2. Edit the `.gitignore` file to ignore certain files and directories:
echo "*.log" > .gitignore
echo "temp/" >> .gitignore
*Explanation*:
- `*.log` ignores all `.log` files.
- `temp/` ignores the entire `temp` directory.
3. Check the status of your repository:
git status
You should see that `file2.log` and `temp/tempfile.txt` are now ignored by Git.

### Step 4: Verify and Commit the `.gitignore` File

1. Add the `.gitignore` file to the staging area:


git add .gitignore

2. Commit the `.gitignore` file:


git commit -m "Add .gitignore to ignore .log files and temp directory"
### Step 5: Practice Ignoring New Files

1. Create new files and directories that match the patterns in `.gitignore`:
echo "Another log file" > anotherfile.log
mkdir temp2
echo "Temporary data 2" > temp2/tempfile2.txt

2. Check the status of your repository again:


git status
You should see that `anotherfile.log` is ignored due to the `*.log` pattern, and
`temp2/tempfile2.txt` is tracked because `temp2/` is not included in `.gitignore`.

### Practice Summary


1. Create a new Git repository and commit initial files.
2. Create and configure a `.gitignore` file to ignore specific files and directories.
3. Verify the ignored files using `git status`.
4. Commit the `.gitignore` file to the repository.
5. Create new files and directories to test the ignore patterns.

### Explanation of Commands and Concepts

- `.gitignore`: A file used to tell Git which files or directories to ignore. The
patterns in the `.gitignore` file follow specific rules to match files and
directories.
- `git status`: Displays the state of the working directory and the staging area,
showing which changes are staged, unstaged, or untracked.
- `git add <file>`: Adds changes to the staging area.
- `git commit -m "<message>"`: Records changes to the repository.
- `touch <file>`: Creates an empty file.

By following these steps, you'll gain hands-on experience with creating and
using a `.gitignore` file, helping you manage which files and directories Git tracks
in your repository.

sample project to practice using `git revert`, `git log`, and `git show` commands.
### Step 1: Set Up the Project

1. Create a new directory for your project and navigate into it:
mkdir git-revert-practice
cd git-revert-practice
2. Initialize a Git repository:
git init
### Step 2: Create and Commit Initial Files

1. Create a new file:


echo "Initial content" > file1.txt
2. Stage and commit the file:
git add file1.txt
git commit -m "Initial commit with file1.txt"
3. Modify the file and commit the change:
echo "Second line of content" >> file1.txt
git add file1.txt
git commit -m "Add second line to file1.txt"
4. Modify the file again and commit the change:
echo "Third line of content" >> file1.txt
git add file1.txt
git commit -m "Add third line to file1.txt"
### Step 3: Practice Using `git log`

1. View the commit history:


git log
*Explanation*: `git log` shows the commit history, including the commit hashes,
author, date, and commit messages.

### Step 4: Practice Using `git show`


1. View details of the most recent commit:
git show
*Explanation*: `git show` without any arguments shows the details of the most
recent commit, including the changes made.

2. View details of a specific commit (replace `<commit-hash>` with an actual


commit hash from the `git log` output):
git show <commit-hash>
*Explanation*: `git show <commit-hash>` shows the details of the specified
commit.

### Step 5: Practice Using `git revert`

1. Revert the most recent commit:


git revert HEAD
*Explanation*: `git revert HEAD` creates a new commit that undoes the changes
of the most recent commit.

2. View the commit history again:


git log
*Explanation*: The commit history will now include the revert commit.

### Practice Summary

1. Create and commit initial files (`file1.txt`).


2. Make additional changes to `file1.txt` and commit those changes.
3. View the commit history using `git log`.
4. View details of commits using `git show`.
5. Revert a commit using `git revert`.

### Explanation of Commands

- `git init`: Initializes a new Git repository.


- `echo "text" > file.txt`: Creates a file with the specified text.
- `git add <file>`: Adds changes to the staging area.
- `git commit -m "<message>"`: Records changes to the repository.
- `git log`: Shows the commit history.
- `git show`: Shows details of a specific commit.
- `git revert <commit>`: Creates a new commit that undoes the changes of the
specified commit.

By following these steps, you'll gain hands-on experience with `git revert`, `git
log`, and `git show`, helping you understand how to manage and inspect
commits in your Git repository.

project to practice using `git reset` with its different options: `--hard`, `--soft`,
and `--mixed`.

### Step 1: Set Up the Project

1. Create a new directory for your project and navigate into it:
mkdir git-reset-practice
cd git-reset-practice
2. Initialize a Git repository:
git init
### Step 2: Create and Commit Initial Files

1. Create a new file:


echo "Initial content" > file1.txt
2. Stage and commit the file:
git add file1.txt
git commit -m "Initial commit with file1.txt"
3. Modify the file and commit the change:
echo "Second line of content" >> file1.txt
git add file1.txt
git commit -m "Add second line to file1.txt"
4. Modify the file again and commit the change:
echo "Third line of content" >> file1.txt
git add file1.txt
git commit -m "Add third line to file1.txt"
### Step 3: Practice Using `git reset --soft`

1. View the commit history:


git log
2. Reset the HEAD to the previous commit (soft reset):
git reset --soft HEAD~1
*Explanation*: `git reset --soft HEAD~1` moves the HEAD pointer to the previous
commit and keeps the changes from the reset commit staged.

3. Check the status to see the staged changes:


git status
4. Recommit the staged changes:
git commit -m "Recommit after soft reset"
### Step 4: Practice Using `git reset --mixed`
1. Modify the file again and commit the change:
echo "Fourth line of content" >> file1.txt
git add file1.txt
git commit -m "Add fourth line to file1.txt"
2. Reset the HEAD to the previous commit (mixed reset):
git reset --mixed HEAD~1
*Explanation*: `git reset --mixed HEAD~1` moves the HEAD pointer to the
previous commit and unstages the changes from the reset commit.

3. Check the status to see the unstaged changes:


git status
4. Stage and recommit the changes:
git add file1.txt
git commit -m "Recommit after mixed reset"
### Step 5: Practice Using `git reset --hard`

1. Modify the file again and commit the change:


echo "Fifth line of content" >> file1.txt
git add file1.txt
git commit -m "Add fifth line to file1.txt"
2. Reset the HEAD to the previous commit (hard reset):
git reset --hard HEAD~1
*Explanation*: `git reset --hard HEAD~1` moves the HEAD pointer to the
previous commit and discards the changes from the reset commit.

3. Check the status to see there are no changes:


git status
4. View the content of the file to confirm changes were discarded:
cat file1.txt
### Practice Summary
1. Create and commit initial files (`file1.txt`).
2. Make additional changes to `file1.txt` and commit those changes.
3. Perform a soft reset to move the HEAD to the previous commit while keeping
changes staged.
4. Perform a mixed reset to move the HEAD to the previous commit while
unstaging changes.
5. Perform a hard reset to move the HEAD to the previous commit and discard
changes.

### Explanation of Commands

- `git init`: Initializes a new Git repository.


- `echo "text" > file.txt`: Creates a file with the specified text.
- `git add <file>`: Adds changes to the staging area.
- `git commit -m "<message>"`: Records changes to the repository.
- `git log`: Shows the commit history.
- `git reset --soft <commit>`: Moves the HEAD pointer to the specified commit
and keeps the changes from the reset commit staged.
- `git reset --mixed <commit>`: Moves the HEAD pointer to the specified commit
and unstages the changes from the reset commit.
- `git reset --hard <commit>`: Moves the HEAD pointer to the specified commit
and discards the changes from the reset commit.
- `cat <file>`: Displays the content of the file.

By following these steps, you'll gain hands-on experience with `git reset` in its
different modes (`--hard`, `--soft`, and `--mixed`), helping you understand how
to manage commits and changes in your Git repository.
explore the differences between `git revert` and `git reset` with examples.

### `git revert`

`git revert` creates a new commit that undoes the changes from a previous
commit. It doesn't change the commit history but adds a new commit to reverse
the specified changes.

#### Example:

1. Set up the project:


mkdir git-revert-example
cd git-revert-example
git init
echo "Initial content" > file.txt
git add file.txt
git commit -m "Initial commit"
2. Make a couple of changes and commit them:
echo "Second line" >> file.txt
git add file.txt
git commit -m "Add second line"

echo "Third line" >> file.txt


git add file.txt
git commit -m "Add third line"
3. Revert the second commit (the commit that added the third line):
git log --oneline
# Find the commit hash for the commit that added the third line, e.g., abc123
git revert abc123
4. View the commit history:
git log --oneline
The `git revert` command will create a new commit that undoes the changes
made in the specified commit. The commit history will remain linear and intact.

### `git reset`

`git reset` changes the current branch's commit history and can modify the
staging area and working directory based on the mode used (`--soft`, `--mixed`,
`--hard`).

#### Example:

1. Set up the project:


mkdir git-reset-example
cd git-reset-example
git init
echo "Initial content" > file.txt
git add file.txt
git commit -m "Initial commit"
2. Make a couple of changes and commit them:
echo "Second line" >> file.txt
git add file.txt
git commit -m "Add second line"
echo "Third line" >> file.txt
git add file.txt
git commit -m "Add third line"
3. View the commit history:
git log --oneline
4. Reset to the first commit:

- Soft Reset:
git reset --soft HEAD~2
git log --oneline
git status
The `git reset --soft` command will move the HEAD pointer to the specified
commit but keep all changes staged. The commit history will be rewritten, but
no changes are lost.

- Mixed Reset:
git reset --mixed HEAD~1
git log --oneline
git status
The `git reset --mixed` command will move the HEAD pointer to the specified
commit and unstage all changes. The commit history will be rewritten, and the
changes will be in the working directory but not staged.

- Hard Reset:
git reset --hard HEAD~1
git log --oneline
git status
The `git reset --hard` command will move the HEAD pointer to the specified
commit and discard all changes. The commit history will be rewritten, and all
changes from the reset commit will be lost.
### Summary of Differences

- `git revert`:
- Creates a new commit that undoes changes from a specified commit.
- Keeps the commit history linear and intact.
- Useful for undoing changes in a collaborative environment without rewriting
history.

- `git reset`:
- Moves the HEAD pointer to a specified commit and optionally modifies the
staging area and working directory.
- Can rewrite commit history and potentially discard changes.
- Useful for undoing commits in a private branch or before sharing with others.
- Modes:
- `--soft`: Keeps changes staged.
- `--mixed`: Keeps changes in the working directory.
- `--hard`: Discards all changes.

By following these examples, you'll gain a clear understanding of how to use `git
revert` and `git reset` in different scenarios.

project to practice using `git branch` and `git checkout` & git merge.

### Step 1: Set Up the Project

1. Create a new directory for your project and navigate into it:
mkdir git-branch-checkout-practice
cd git-branch-checkout-practice
2. Initialize a Git repository:
git init
### Step 2: Create and Commit Initial Files

1. Create a new file:


echo "Initial content" > file1.txt
2. Stage and commit the file:
git add file1.txt
git commit -m "Initial commit with file1.txt"
### Step 3: Create and Switch Branches

1. Create a new branch named `feature-branch`:


git branch feature-branch
2. List all branches:
git branch
*Explanation*: The current branch is indicated with an asterisk `*`. You should
see `main` (or `master`) and `feature-branch`.

3. Switch to the new branch:


git checkout feature-branch
4. Make changes on `feature-branch`:
echo "Feature branch content" >> file1.txt
git add file1.txt
git commit -m "Add feature branch content to file1.txt"
5. Switch back to the main branch:
git checkout main
6. Check the content of the file on `main` branch:
cat file1.txt
*Explanation*: You should only see the initial content because the changes
made in `feature-branch` are not yet in `main`.
### Step 4: Create Another Branch and Make Changes

1. Create a new branch named `bugfix-branch` and switch to it:


git checkout -b bugfix-branch
2. Make changes on `bugfix-branch`:
echo "Bugfix branch content" >> file1.txt
git add file1.txt
git commit -m "Add bugfix branch content to file1.txt"
3. Switch back to the main branch:
git checkout main
4. Check the content of the file on `main` branch:
cat file1.txt
*Explanation*: Again, you should only see the initial content.

### Step 5: Merge Branches

1. Merge `feature-branch` into `main`:


git merge feature-branch
2. Check the content of the file after the merge:
cat file1.txt
*Explanation*: You should see the initial content followed by the content added
in `feature-branch`.

3. Merge `bugfix-branch` into `main`:


git merge bugfix-branch
4. Check the content of the file after the second merge:
cat file1.txt
*Explanation*: You should see the initial content followed by the content from
both `feature-branch` and `bugfix-branch`.

### Summary of Commands

1. Create and switch branches:


- `git branch <branch-name>`: Creates a new branch.
- `git checkout <branch-name>`: Switches to the specified branch.
- `git checkout -b <branch-name>`: Creates a new branch and switches to it.
2. Make changes and commit them:
- `echo "text" >> file.txt`: Adds text to the file.
- `git add <file>`: Adds changes to the staging area.
- `git commit -m "<message>"`: Records changes to the repository.

3. Merge branches:
- `git merge <branch-name>`: Merges the specified branch into the current
branch.

### Explanation of Commands

- `git init`: Initializes a new Git repository.


- `echo "text" > file.txt`: Creates a file with the specified text.
- `echo "text" >> file.txt`: Appends text to the file.
- `git add <file>`: Adds changes to the staging area.
- `git commit -m "<message>"`: Records changes to the repository.
- `git branch <branch-name>`: Creates a new branch.
- `git branch`: Lists all branches.
- `git checkout <branch-name>`: Switches to the specified branch.
- `git checkout -b <branch-name>`: Creates a new branch and switches to it.
- `git merge <branch-name>`: Merges the specified branch into the current
branch.
- `cat <file>`: Displays the content of the file.

By following these steps, you'll gain hands-on experience with `git branch` and
`git checkout`, helping you manage branches effectively in your Git repository.

DevOps Training
WhatsApp *91 8886740600*

Preethi Dovala

akshay alone

Home


Syllabus


Live Training


Video Tutorials

 Policies

Blog


Home

GIT - Day-3
QUIZ

project to practice resolving Git conflicts.

### Step 1: Set Up the Project

1. Create a new directory for your project and navigate into it:
mkdir git-conflict-practice
cd git-conflict-practice
2. Initialize a Git repository:
git init
### Step 2: Create and Commit Initial Files

1. Create a new file:


echo "Initial content" > file.txt
2. Stage and commit the file:
git add file.txt
git commit -m "Initial commit with file.txt"
### Step 3: Create and Switch Branches
1. Create a new branch named `branch1`:
git branch branch1
2. Create another branch named `branch2`:
git branch branch2
### Step 4: Make Conflicting Changes on Both Branches

1. Switch to `branch1` and make changes:


git checkout branch1
echo "Changes in branch1" >> file.txt
git add file.txt
git commit -m "Add changes in branch1"
2. Switch to `branch2` and make conflicting changes:
git checkout branch2
echo "Conflicting changes in branch2" >> file.txt
git add file.txt
git commit -m "Add conflicting changes in branch2"
### Step 5: Merge Branches and Resolve Conflicts

1. Switch back to the main branch:


git checkout main
2. Merge `branch1` into `main`:
git merge branch1
*Explanation*: This merge should succeed without any conflicts.

3. Merge `branch2` into `main`:


git merge branch2
*Explanation*: This merge will produce a conflict because both `branch1` and
`branch2` modified `file.txt`.

4. Git will show a message indicating there are conflicts. Open `file.txt` to see
the conflict markers:
cat file.txt
The content will look something like this:
txt
Initial content
Changes in branch1
<<<<<<< HEAD
=======
Conflicting changes in branch2
>>>>>>> branch2

5. Resolve the conflict by editing the file. You can manually choose how to
combine the changes:
txt
Initial content
Changes in branch1
Conflicting changes in branch2
6. Stage the resolved file:
git add file.txt
7. Commit the merge:
git commit -m "Resolve merge conflict between branch1 and branch2"
### Step 6: Verify the Merge

1. Check the Git log to verify the merge:


git log --oneline

You should see a merge commit with the message you provided.

### Explanation of Commands


- `git init`: Initializes a new Git repository.
- `echo "text" > file.txt`: Creates a file with the specified text.
- `echo "text" >> file.txt`: Appends text to the file.
- `git add <file>`: Adds changes to the staging area.
- `git commit -m "<message>"`: Records changes to the repository.
- `git branch <branch-name>`: Creates a new branch.
- `git checkout <branch-name>`: Switches to the specified branch.
- `git merge <branch-name>`: Merges the specified branch into the current
branch.
- `cat <file>`: Displays the content of the file.
- `git log --oneline`: Shows the commit history in a compact format.

By following these steps, you'll gain hands-on experience with creating,


resolving, and committing merge conflicts in Git.

###Project to Practice Git Stash with a Scenario

In this sample project, you'll work through a scenario where you're developing a
new feature but need to quickly fix a bug in the main branch. You'll use Git stash
to save your work on the feature, switch to the main branch to fix the bug, and
then return to your feature development.

### Step 1: Set Up the Project

1. Create a new directory for your project and navigate into it:
mkdir git-stash-scenario
cd git-stash-scenario
2. Initialize a Git repository:
git init
3. Create and commit initial files:
echo "Initial content" > main.txt
git add main.txt
git commit -m "Initial commit with main.txt"
### Step 2: Start Developing a New Feature

1. Create a new branch for the feature:


git checkout -b feature-branch
2. Make some changes to `main.txt` and create a new file for the feature:
echo "Feature development in progress" >> main.txt
echo "Feature-specific content" > feature.txt
3. Stage the changes but don't commit them yet:
git add main.txt feature.txt
### Step 3: Handle an Urgent Bug Fix

1. Switch back to the `main` branch:


git checkout main
*Note*: Git will prevent you from switching branches if you have uncommitted
changes. This is where Git stash comes in handy.

2. Stash your changes:


git stash
3. Verify that your changes are stashed:
git stash list
You should see a stash entry like `stash@{0}: WIP on feature-branch: <commit-
hash> <commit-message>`.
4. Fix the bug in the `main` branch:
echo "Bug fix" >> main.txt
git add main.txt
git commit -m "Fix a critical bug"
### Step 4: Return to Feature Development

1. Switch back to your feature branch:


git checkout feature-branch
2. Apply your stashed changes:
git stash pop
This will apply the stashed changes and remove the stash entry.

3. Verify the changes are back:


cat main.txt
cat feature.txt
You should see your feature development content and the bug fix in `main.txt`
and the `feature.txt` file back.

4. Continue working on your feature and commit the changes:


echo "More feature development" >> feature.txt
git add main.txt feature.txt
git commit -m "Continue feature development after bug fix"
### Step 5: Additional Stash Operations (Optional)

1. Create another change and stash it with a message:


echo "Temporary changes" >> feature.txt
git stash save "Temporary changes for testing"
2. List all stashes:
git stash list
3. Show the details of the stash:
git show stash@{0}
4. Apply the stash without removing it from the list:
git stash apply stash@{0}
5. Drop the stash:
git stash drop stash@{0}
6. Stash changes interactively:
echo "Interactive stash" >> feature.txt
git stash -p
7. Stash including untracked files:
touch untracked_file.txt
git stash -u
8. Clear all stashes:
git stash clear
By following these steps, you'll gain practical experience using Git stash
commands to save and manage your work in progress, especially when handling
urgent interruptions.

project that helps you practice the git rebase command with a realistic scenario.

Scenario: Feature Development with Rebase In this scenario, you'll be working


on a feature in a separate branch while other changes are being made to the
main branch. You'll use git rebase to integrate changes from the main branch
into your feature branch.

### Step 1: Set Up the Project

1. Create a new directory for your project and navigate into it:
mkdir git-rebase-practice
cd git-rebase-practice
2. Initialize a Git repository:
git init
3. Create and commit initial files:
echo "Initial content" > main.txt
git add main.txt
git commit -m "Initial commit with main.txt"
### Step 2: Create and Switch Branches

1. Create a new branch for feature development:


git checkout -b feature-branch
2. Make some changes and commit them in the feature branch:
echo "Feature work 1" >> feature.txt
git add feature.txt
git commit -m "Add feature work 1"

echo "Feature work 2" >> feature.txt


git add feature.txt
git commit -m "Add feature work 2"
### Step 3: Simulate Changes in the Main Branch

1. Switch back to the `main` branch:


git checkout main
2. Make some changes and commit them in the main branch:
echo "Main branch work 1" >> main.txt
git add main.txt
git commit -m "Add main branch work 1"

echo "Main branch work 2" >> main.txt


git add main.txt
git commit -m "Add main branch work 2"
### Step 4: Rebase Feature Branch onto Main Branch
1. Switch back to the feature branch:
git checkout feature-branch
2. Rebase the feature branch onto the main branch:
git rebase main
*Explanation*: This moves the feature branch commits to be based on top of
the latest commit in the main branch, resulting in a linear history.

### Step 5: Resolve Any Conflicts

1. If there are any conflicts during the rebase, Git will pause and prompt you to
resolve them. For example, if both branches modified the same part of a file,
you'll see conflict markers in the file:
cat main.txt
The content might look like this:
txt
Initial content
Main branch work 1
<<<<<<< HEAD
Main branch work 2
=======
Feature work 2
>>>>>>> feature-branch
2. Resolve the conflict manually by editing the file:
txt
Initial content
Main branch work 1
Main branch work 2
Feature work 2
3. Stage the resolved file:
git add main.txt
4. Continue the rebase:
git rebase --continue
5. Repeat steps 1-4 for any additional conflicts.

### Step 6: Verify the Rebase

1. Check the commit history:


git log --oneline
You should see a linear history with your feature branch commits on top of the
main branch commits.

### Explanation of Commands

- `git init`: Initializes a new Git repository.


- `echo "text" >> file.txt`: Appends text to the file.
- `git add <file>`: Adds changes to the staging area.
- `git commit -m "<message>"`: Records changes to the repository.
- `git checkout -b <branch-name>`: Creates and switches to a new branch.
- `git rebase <branch-name>`: Reapplies commits on top of another base tip.
- `git rebase --continue`: Continues the rebase after resolving conflicts.
- `git log --oneline`: Shows the commit history in a compact format.

By following these steps, you'll gain hands-on experience with the `git rebase`
command and understand how it helps create a cleaner, linear commit history.
DevOps Training
WhatsApp *91 8886740600*

Preethi Dovala

akshay alone

Home


Syllabus


Live Training


Video Tutorials

 Policies

Blog


Home

GIT - Day-4
QUIZ

### Step-by-Step Guide: Sample Project for Git and GitHub


#### Scenario Overview
In this project, you'll practice setting up a GitHub account, creating a repository,
generating a Personal Access Token (PAT), creating a local Git repository,
connecting it to the GitHub repository, push changes, and managing branches
both locally and remotely.

---

### Step 1: Create a GitHub Account and Repository

1. Create a GitHub Account:


- Go to [GitHub](https://github.com) and sign up for a new account if you don’t
have one.

2. Create a Repository on GitHub:


- Log in to your GitHub account.
- Click on the "+" icon in the upper right corner and select "New repository."
- Name your repository, e.g., `sample-project`.
- Optionally, you can add a README file (we'll create one locally later).
- Click "Create repository."

---

### Step 2: Create a Personal Access Token (PAT) on GitHub

1. Purpose of a Personal Access Token:


- A PAT is an alternative to using a password when performing Git operations via
the command line. It is used for authentication to allow secure access to your
GitHub repositories.

2. Create a Personal Access Token:


- Go to your GitHub profile and click on "Settings."
- Scroll down to "Developer settings" and click on "Personal access tokens" >
"Tokens (classic)."
- Click "Generate new token."
- Provide a note (e.g., `My first PAT`) and set the expiration (e.g., 90 days).
- Select the `repo` scope to give full control over private repositories.
- Click "Generate token."
- Important: Copy the token and store it securely, as you won't be able to see it
again.

---

### Step 3: Set Up a Local Git Repository and Connect to GitHub

1. Create a Local Git Repository:


- Open your terminal (or command prompt) and navigate to your project
directory:
mkdir sample-project
cd sample-project
- Initialize a Git repository:
git init
2. Create a README File:
- Create a simple README file:
echo "# Sample Project" > README.md
3. Stage and Commit the File:
- Add the file to the staging area and commit:
git add README.md
git commit -m "Initial commit with README"
4. Connect to the GitHub Repository:
- Add the remote repository URL (replace `your-username` with your GitHub
username):
git remote add origin https://github.com/your-username/sample-project.git
5. Pu the Code to GitHub:
- Pu the local repository to the remote repository on GitHub:
git pu -u origin main
- When prompted, use your GitHub username and paste the Personal Access
Token as the password.

---

### Step 4: Validate the Remote Branch

1. List All Branches:


- Check the branches on the remote repository:
git branch -r
- You Could see `origin/main`.

2. Verify on GitHub:
- Go to your GitHub repository page and ensure that the `main` branch is visible
and contains the committed files.
---

### Step 5: Delete the Local Branch

1. Create and Switch to a New Branch:


- Create a new branch and switch to it:
git checkout -b feature-branch
2. Push the Feature Branch to GitHub:
- Push the new branch to GitHub:
git push -u origin feature-branch
3. Switch Back to the `main` Branch:
- Switch back to the `main` branch:
git checkout main
4. Delete the Local Branch:
- Delete the local `feature-branch`:
git branch -d feature-branch
---
### Step 6: Delete the Remote Branch

1. Delete the Remote Branch:


- Remove the `feature-branch` from the remote repository:
git pu origin --delete feature-branch
2. Verify Deletion on GitHub:
- Go to your GitHub repository page and check that the `feature-branch` is no
longer listed under branches.
---
By following these steps, you'll gain practical experience in setting up and
managing GitHub repositories, working with local Git repositories, and handling
branches both locally and remotely.

expand the previous scenario to include multiple branches, allowing you to


practice more advanced Git operations, such as merging and resolving conflicts.

### Scenario Overview


In this extended project, you'll create multiple branches to simulate a
collaborative workflow. You'll practice creating and merging branches, resolving
conflicts, and managing branches both locally and remotely.
---

### Step 1: Create a GitHub Account and Repository (As Before)

1. Create a GitHub Account:


- Go to [GitHub](https://github.com) and sign up for a new account if you don’t
have one.

2. Create a Repository on GitHub:


- Log in to your GitHub account.
- Click on the "+" icon in the upper right corner and select "New repository."
- Name your repository, e.g., `sample-multi-branch-project`.
- Click "Create repository."
---
### Step 2: Create a Personal Access Token (PAT) on GitHub (As Before)

1. Create a Personal Access Token:


- Go to your GitHub profile, navigate to "Settings," then "Developer settings" >
"Personal access tokens" > "Tokens (classic)."
- Generate a new token with the `repo` scope.
- Copy and securely store the token.
--

### Step 3: Set Up the Project Locally and Connect to GitHub

1. Create a Local Git Repository:


- Open your terminal (or command prompt) and navigate to your project
directory:

mkdir sample-multi-branch-project
cd sample-multi-branch-project
- Initialize a Git repository:

git init
2. Create and Commit an Initial File:
- Create a README file:

echo "# Sample Multi-Branch Project" > README.md


- Add and commit the file:
git add README.md
git commit -m "Initial commit with README"
3. Connect to the GitHub Repository:
- Add the remote repository URL:

git remote add origin https://github.com/your-username/sample-multi-branch-


project.git
4. Push the Code to GitHub:
- Push the local repository to GitHub:

git push -u origin main


- Authenticate using your GitHub username and PAT.
---

### Step 4: Create Multiple Branches Locally and Push to GitHub

1. Create and Switch to a `dev` Branch:


- Create a `dev` branch:

git checkout -b dev


- Make some changes:

echo "Development work" > dev.txt


git add dev.txt
git commit -m "Add development work in dev branch"
- Push the `dev` branch to GitHub:
git push -u origin dev
2. Create and Switch to a `feature-a` Branch from `dev`:
- Create `feature-a` branch:

git checkout -b feature-a


- Make some changes:

echo "Feature A work" > feature-a.txt


git add feature-a.txt
git commit -m "Add work on Feature A"
- Push the `feature-a` branch to GitHub:

git push -u origin feature-a


3. Create and Switch to a `feature-b` Branch from `dev`:
- Create `feature-b` branch:

git checkout -b feature-b


- Make some changes:

echo "Feature B work" > feature-b.txt


git add feature-b.txt
git commit -m "Add work on Feature B"
- Push the `feature-b` branch to GitHub:

git push -u origin feature-b


---
### Step 5: Merge Branches and Resolve Conflicts

1. Merge `feature-a` into `dev`:


- Switch to the `dev` branch:

git checkout dev


- Merge `feature-a`:

git merge feature-a


- Resolve any conflicts if necessary, then commit the merge:

git add .
git commit -m "Merge feature-a into dev"
2. Merge `feature-b` into `dev`:
- Merge `feature-b` into `dev`:

git merge feature-b


- If there are conflicts, resolve them and commit the merge:

git add .
git commit -m "Merge feature-b into dev"
3. Push the Updated `dev` Branch to GitHub:
- Push the merged changes:

git push origin dev


---
### Step 6: Validate and Clean Up Branches

1. List Remote Branches:


- List all branches on GitHub:

git branch -r
- You should see `origin/main`, `origin/dev`, `origin/feature-a`, and
`origin/feature-b`.

2. Delete Local Feature Branches:


- Delete `feature-a` and `feature-b` locally:

git branch -d feature-a


git branch -d feature-b
3. Delete Remote Feature Branches:
- Delete `feature-a` and `feature-b` from GitHub:

git push origin --delete feature-a


git push origin --delete feature-b
4. Verify Deletion on GitHub:
- Go to your GitHub repository and ensure that `feature-a` and `feature-b`
branches are no longer listed.
---

### Step 7: Merge `dev` into `main` and Final Cleanup


1. Merge `dev` into `main`:
- Switch to the `main` branch:

git checkout main


- Merge the `dev` branch:

git merge dev


- Resolve any conflicts, if necessary, then commit the merge:

git add .
git commit -m "Merge dev into main"
2. Push the Final `main` Branch to GitHub:
- Push the `main` branch with merged changes:

git push origin main


3. Delete the `dev` Branch Locally and Remotely:
- Delete the `dev` branch locally:

git branch -d dev


- Delete the `dev` branch from GitHub:

git push origin --delete dev


4. Verify Final State on GitHub:
- Ensure only the `main` branch remains on GitHub, with all changes merged.
---
This scenario covers the full lifecycle of a project with multiple branches, from
creation to merging and cleanup. It helps you practice core Git operations,
including managing branches both locally and remotely, and resolving conflicts.

### Sample Project for Practicing `git clone`, `git pull`, and `git fetch`

#### Overview
In this project, you'll simulate a collaborative workflow where multiple team
members work on a shared GitHub repository. You'll practice cloning a
repository, fetching updates, and pulling the latest changes from the remote
repository.
---

### Step 1: Understanding the Commands

1. `git clone`:
- What it does: `git clone` is used to create a copy of an existing Git repository
from a remote server (like GitHub) to your local machine. It copies all the files,
branches, and commit history from the remote repository.
- Scenario: You join a new project, and you need to set up the project on your
local machine by cloning the repository from GitHub.

2. `git pull`:
- What it does: `git pull` is a combination of `git fetch` and `git merge`. It fetches
changes from the remote repository and immediately tries to merge them into
your current branch. If there are any conflicts, you need to resolve them before
completing the merge.
- Scenario: You’ve been working on a project, but before you start new work,
you need to pull the latest changes from the remote repository to ensure you’re
up to date.

3. `git fetch`:
- What it does: `git fetch` retrieves updates from the remote repository but does
not automatically merge them into your working branch. It updates your local
copy of the remote branches, allowing you to review changes before merging.
- Scenario: You want to see what changes have been made in the remote
repository without immediately merging them into your local branch.
---

### Step 2: Set Up the GitHub Repository

1. Create a GitHub Repository:


- Go to GitHub and create a new repository named `collaborative-project`.
- Add a README file, a `.gitignore` file, and a license if needed.
- Click "Create repository."

2. Add Some Initial Files:


- On GitHub, add a few files (e.g., `index.html`, `style.css`, `script.js, or
readme.txt`), or make some initial commits to simulate the repository having
existing work.
---

### Step 3: Clone the Repository

1. Clone the Repository to Your Local Machine:


- Open your terminal or command prompt.
- Navigate to the directory where you want to clone the repository.
- Run the `git clone` command:
git clone https://github.com/your-username/collaborative-project.git
- This will create a directory named `collaborative-project` containing all the
files and history from the remote repository.

2. Verify the Cloned Repository:


- Navigate into the cloned repository:
cd collaborative-project
- List the files to ensure everything is there:
ls
- Check the remote URL:
git remote -v
- This should show the URL of the GitHub repository.
---

### Step 4: Simulate Updates from Another Developer

1. Make Changes on GitHub:


- Imagine another developer (or yourself in another browser) makes changes
directly on GitHub.
- For example, add a new file `new-feature.txt` or modify an existing file like
`index.html`.
- Commit the changes directly on GitHub.
--

### Step 5: Fetch Changes Without Merging (`git fetch`)


1. Fetch Updates from the Remote Repository:
- While still in your cloned repository on your local machine, fetch the latest
changes:
git fetch origin
- This command downloads updates from the remote repository without
merging them into your current branch.

2. Check the Fetched Changes:


- After fetching, you can check which branches were updated:
git branch -r
- To see the changes in the fetched branch, you can compare it with your
current branch:
git diff origin/main
---

### Step 6: Pull Changes and Merge (`git pull`)

1. Pull Updates from the Remote Repository:


- After reviewing the fetched changes, pull the latest updates:
git pull origin main
- This will fetch the changes and merge them into your current branch (`main` in
this case).
- If there are conflicts, Git will prompt you to resolve them.

2. Resolve Any Conflicts:


- If conflicts occur, open the conflicting files, resolve the differences, and then
complete the merge:
git add .
git commit -m "Resolved merge conflicts"
---
### Step 7: Simulate a Scenario with Multiple Developers

1. Clone the Repository Again in a Different Directory:


- Simulate another developer by cloning the repository in a different directory
or on a different machine:
git clone https://github.com/your-username/collaborative-project.git
developer-2
cd developer-2
2. Make Changes in the Second Clone:
- Add a new file or modify an existing file in the second clone, then commit the
changes:
echo "Some new content" > new-feature.txt
git add new-feature.txt
git commit -m "Add new feature"
3. Push Changes to the Remote Repository:
- Push the changes to GitHub from the second clone:
git push origin main
4. Return to the First Clone and Pull the Latest Changes:
- Go back to the first clone and pull the latest changes:
cd ../collaborative-project
git pull origin main
- This will bring the changes made by the "second developer" into the first
clone.
---
This scenario helps you understand the differences between `git clone`, `git
fetch`, and `git pull`, and provides a practical context for using these commands
in a collaborative environment.

### Project: Handling a File Conflict Between Local and Remote Repositories
#### Overview
In this project, you'll simulate a scenario where a file with the same name but
different content is created in both your local repository and the remote
repository. You'll then attempt to push your local changes to the remote
repository, which will result in a conflict. This scenario will help you practice
resolving conflicts and understanding how Git handles these situations.

### Step 1: Set Up the GitHub Repository

1. Create a GitHub Repository:


- Go to GitHub and create a new repository named `conflict-demo`.
- Add a README file to initialize the repository, then click "Create repository."

2. Clone the Repository to Your Local Machine:


- Open your terminal (or command prompt) and clone the repository:
git clone https://github.com/your-username/conflict-demo.git
- Navigate into the cloned repository:
cd conflict-demo

### Step 2: Create a File in the Remote Repository

1. Create a File Directly on GitHub:


- Go to the `conflict-demo` repository on GitHub.
- Click "Add file" > "Create new file."
- Name the file `conflict.txt`.
- Add some content to the file, for example:
This content was added directly on GitHub.
- Scroll down and commit the new file by clicking "Commit new file."

2. Verify the File on GitHub:


- Ensure that the `conflict.txt` file now exists in the repository on GitHub with
the content you added.

### Step 3: Create a Different Version of the Same File Locally

1. Create a Different Version of `conflict.txt` Locally:


- In your local `conflict-demo` repository, create the `conflict.txt` file with
different content:
echo "This content was added locally." > conflict.txt
- Add and commit the file locally:
git add conflict.txt
git commit -m "Add conflict.txt with local content"
2. Attempt to Push the Local Changes to GitHub:
- Try to push your changes to the remote repository:
git push origin main
3. Observe the Conflict:
- Git will reject the push because the `conflict.txt` file already exists in the
remote repository with different content. You'll see an error message
suggesting you need to pull first.

### Step 4: Resolve the Conflict


1. Pull the Remote Changes to Your Local Repository:
- Pull the changes from the remote repository:
git pull origin main
- Git will attempt to merge the changes and will detect a conflict in the
`conflict.txt` file.

2. Resolve the Conflict:


- Open the `conflict.txt` file in a text editor. You’ll see conflict markers like this:
<<<<<<< HEAD
This content was added locally.
=======
This content was added directly on GitHub.
>>>>>>> origin/main
- Edit the file to resolve the conflict. You can choose to keep one version,
combine both, or make other modifications. For example:
This content was added locally.
This content was added directly on GitHub.
- After resolving the conflict, save the file.

3. Commit the Resolved Conflict:


- Add the resolved file to the staging area and commit the changes:
git add conflict.txt
git commit -m "Resolve conflict in conflict.txt"
4. Push the Resolved Changes to GitHub:
- Push your changes to the remote repository:
git push origin main
### Step 5: Verify the Final State

1. Check the Remote Repository on GitHub:


- Go back to the `conflict-demo` repository on GitHub.
- Verify that the `conflict.txt` file has been updated with the resolved content.
2. Check the Commit History:
- On GitHub, look at the commit history to see the merge commit that resolved
the conflict.

This scenario helps you understand how Git handles conflicts when the same file
has different content in the local and remote repositories. By practicing this, you
can get comfortable with resolving conflicts in real-world situations.

### Project: Handling a File Conflict with `git pull --rebase`

#### Overview
This project will guide you through a scenario where you create a file with the
same name but different content in both your local repository and the remote
repository. You will then use `git pull --rebase` to integrate the changes from the
remote repository, which will result in a conflict. This scenario will help you
practice resolving conflicts during a rebase.

### Step 1: Set Up the GitHub Repository

1. Create a GitHub Repository:


- Go to GitHub and create a new repository named `rebase-conflict-demo`.
- Add a README file to initialize the repository, then click "Create repository."

2. Clone the Repository to Your Local Machine:


- Open your terminal (or command prompt) and clone the repository:
git clone https://github.com/your-username/rebase-conflict-demo.git
- Navigate into the cloned repository:
cd rebase-conflict-demo

### Step 2: Create a File in the Remote Repository

1. Create a File Directly on GitHub:


- Go to the `rebase-conflict-demo` repository on GitHub.
- Click "Add file" > "Create new file."
- Name the file `rebase-conflict.txt`.
- Add some content to the file, for example:
This content was added directly on GitHub.
- Scroll down and commit the new file by clicking "Commit new file."

2. Verify the File on GitHub:


- Ensure that the `rebase-conflict.txt` file now exists in the repository on GitHub
with the content you added.

### Step 3: Create a Different Version of the Same File Locally

1. Create a Different Version of `rebase-conflict.txt` Locally:


- In your local `rebase-conflict-demo` repository, create the `rebase-conflict.txt`
file with different content:
echo "This content was added locally." > rebase-conflict.txt
- Add and commit the file locally:
git add rebase-conflict.txt
git commit -m "Add rebase-conflict.txt with local content"
2. Attempt to Push the Local Changes to GitHub:
- Try to push your changes to the remote repository:
git push origin main
- Git will reject the push because the `rebase-conflict.txt` file already exists in
the remote repository with different content. You'll see an error message
suggesting you need to pull first.

### Step 4: Resolve the Conflict with `git pull --rebase`

1. Pull the Remote Changes with Rebase:


- Instead of a regular `git pull`, you'll rebase your changes on top of the latest
remote changes:
git pull --rebase origin main
- Git will attempt to rebase your changes, but since there is a conflict in the
`rebase-conflict.txt` file, Git will pause and notify you of the conflict.

2. Resolve the Conflict:


- Open the `rebase-conflict.txt` file in a text editor. You’ll see conflict markers
like this:
<<<<<<< HEAD
This content was added directly on GitHub.
=======
This content was added locally.
>>>>>>> YOUR_COMMIT_HASH
- Edit the file to resolve the conflict. For example, you could combine both
versions:
This content was added locally.
This content was added directly on GitHub.
- After resolving the conflict, save the file.

3. Continue the Rebase:


- After resolving the conflict, you need to stage the resolved file:
git add rebase-conflict.txt
- Then, continue the rebase process:
git rebase --continue
- Git will finish applying your changes on top of the latest remote changes.

4. Push the Resolved Changes to GitHub:


- Finally, push your changes to the remote repository:
git push origin main
### Step 5: Verify the Final State

1. Check the Remote Repository on GitHub:


- Go back to the `rebase-conflict-demo` repository on GitHub.
- Verify that the `rebase-conflict.txt` file has been updated with the resolved
content.

2. Check the Commit History:


- On GitHub, review the commit history to see the result of the rebase and the
conflict resolution.

This scenario helps you understand how to handle conflicts during a rebase
using `git pull --rebase`, giving you practical experience with one of the more
complex aspects of Git.
DevOps Training
WhatsApp *91 8886740600*

Preethi Dovala

akshay alone

Home


Syllabus


Live Training


Video Tutorials

 Policies

Blog


Home

GIT - Day-5
QUIZ
### Scenario 1: Practicing Pull Requests

#### Overview
In this scenario, you'll work on a shared repository and create a pull request to
merge your changes into the main branch. This is a common workflow in
collaborative projects.

#### Step-by-Step Instructions

1. Create a GitHub Repository:


- Go to GitHub and create a new repository named `pull-request-demo`.
- Initialize the repository with a README file.

2. Clone the Repository Locally:


- Open your terminal and clone the repository:
git clone https://github.com/your-username/pull-request-demo.git
- Navigate into the cloned repository:
cd pull-request-demo
3. Create a New Branch:
- Create a new branch for your feature or bug fix:
git checkout -b new-feature
4. Make Changes in the New Branch:
- Edit the README file or create a new file named `feature.txt` with some
content:
echo "This is a new feature." > feature.txt
- Stage and commit your changes:
git add feature.txt
git commit -m "Add new feature"
5. Push the New Branch to GitHub:
- Push your new branch to the remote repository:
git push origin new-feature
6. Create a Pull Request on GitHub:
- Go to the `pull-request-demo` repository on GitHub.
- You'll see an option to compare & pull request for your recently pushed
branch. Click on "Compare & pull request."
- Add a title and description for your pull request, then click "Create pull
request."

7. Review and Merge the Pull Request:


- After creating the pull request, you or another collaborator can review the
changes.
- If everything looks good, click "Merge pull request" to merge the changes into
the main branch.

8. Delete the Feature Branch (Optional):


- Once the pull request is merged, you can delete the feature branch:
git branch -d new-feature
- On GitHub, you can also delete the remote branch from the pull request page.

### Scenario 2: Practicing Forks

#### Overview
In this scenario, you'll fork a public repository, make changes in your fork, and
then create a pull request to suggest your changes to the original repository.
1. Fork a Public Repository on GitHub:
- Find a public repository you want to contribute to (you can use any public
repository for practice).
- On the repository's GitHub page, click the "Fork" button at the top-right corner
to create a fork under your GitHub account.

2. Clone Your Fork Locally:


- Clone the forked repository to your local machine:
git clone https://github.com/your-username/fork-demo.git
- Navigate into the cloned repository:
cd fork-demo
3. Set the Original Repository as an Upstream Remote:
- Add the original repository as an upstream remote to keep your fork updated:
git remote add upstream https://github.com/original-username/original-
repository.git
- Verify the remotes:
git remote -v
4. Sync Your Fork with the Upstream Repository:
- Fetch the latest changes from the upstream repository:
git fetch upstream
- Merge the changes into your local main branch:
git checkout main
git merge upstream/main
5. Create a New Branch for Your Changes:
- Create a new branch for your changes:
git checkout -b my-contribution
6. Make and Commit Your Changes:
- Make your desired changes in the repository.
- Stage and commit your changes:
git add .
git commit -m "Fix issue or add a feature"
7. Push Your Branch to Your Fork:
- Push your branch to your fork on GitHub:
git push origin my-contribution
8. Create a Pull Request to the Original Repository:
- Go to your fork on GitHub.
- You'll see an option to "Compare & pull request" for your recently pushed
branch. Click on "Compare & pull request."
- Ensure the base repository is the original repository and the base branch is
`main or master`.
- Add a title and description, then click "Create pull request."

9. Review and Discuss the Pull Request:


- Collaborators of the original repository will review your pull request.
- You may receive feedback and requests for changes. You can make further
commits to the same branch to address these requests.
- Once approved, your changes may be merged into the original repository.

These scenarios will help you practice and understand the workflows for
creating pull requests and working with forks in GitHub.

DevOps Training
WhatsApp *91 8886740600*
Preethi Dovala
akshay alone

Home

Syllabus

Live Training

Video Tutorials

 Policies

Blog


< Back
Linux -Day-1
### Project: Basic Linux- Command Line Practice

#### Scenario:
You have just logged into a new Linux server as a regular user. Your task is to
navigate the file system, manage directories and files, gather system
information, and understand basic user management concepts. This project will
guide you through a sequence of commands that are essential for everyday
tasks in a Linux environment.

1. `clear` - Clear the Terminal Screen


- Objective: Start with a clean terminal.
- Command:
clear
2. `pwd` - Print Working Directory
- Objective: Confirm your current location in the file system.
- Command:
pwd
- Expected Output: Display the full path of the current directory (e.g.,
`/home/username`).

3. `cd ..` - Change to Parent Directory


- Objective: Move up one level in the directory structure.
- Command:
cd ..
4. `cd ~` - Change to Home Directory
- Objective: Return to your home directory.
- Command:
cd ~
5. `mkdir` - Make a New Directory
- Objective: Create a directory named `practice_dir` in your home directory.
- Command:
mkdir practice_dir
6. `ls` - List Directory Contents
- Objective: Verify that the `practice_dir` directory has been created.
- Command:
ls
7. `cd` - Change to a Specific Directory
- Objective: Navigate into the `practice_dir` directory.
- Command:
cd practice_dir
pwd
8. `echo` - Display a Line of Text
- Objective: Create a text file named `sample.txt` with the content "Hello,
Linux!".
- Command:
echo "Hello, Linux!" > sample.txt
9. `cat` - Concatenate and Display File Content
- Objective: Display the contents of `sample.txt`.
- Command:
cat sample.txt
10. `cp` - Copy Files and Directories
- Objective: Copy `sample.txt` to a new file named `sample_copy.txt`.
- Command:
cp sample.txt sample_copy.txt
11. `mv` - Move or Rename Files and Directories
- Objective: Rename `sample_copy.txt` to `sample_renamed.txt`.
- Command:
mv sample_copy.txt sample_renamed.txt
12. `rm` - Remove Files or Directories
- Objective: Delete `sample_renamed.txt`.
- Command:
rm sample_renamed.txt
13. `rm -rf` - Remove Files or Directories Forcefully
- Objective: Delete the `practice_dir` directory and its contents.
- Command:
cd ~
rm -rf practice_dir
14. `uname -a` - Display System Information
- Objective: Get detailed information about the system.
- Command:
uname -a
15. `/etc/os-release` - Display Operating System Information
- Objective: Check the OS version and details.
- Command:
cat /etc/os-release
16. `lscpu` - Display CPU Information
- Objective: View details about the CPU.
- Command:
lscpu
17. `lsmemory` - Display Memory Information
- Objective: View details about the system memory.
- Command:
lsmemory
18. File System Basics
- Objective: Understand how files and directories are organized in Linux. Discuss
the hierarchical structure of directories, starting from the root `/`.
- Explanation: The root directory `/` is the top of the file system hierarchy. All
other directories and files branch out from here.

19. User Management Basics


- Objective: Understand the basics of user accounts and groups. Discuss the
importance of `/etc/passwd` and `/etc/group` files.
- Explanation: Each user has an account with a unique username. Users can be
part of one or more groups, which help manage permissions.

20. Absolute Path vs. Relative Path


- Objective: Understand the difference between absolute and relative paths.
- Explanation:
- Absolute Path: Specifies the full path from the root directory (e.g.,
`/home/username/practice_dir`).
- Relative Path: Specifies the path relative to the current directory (e.g.,
`./practice_dir`).

21. Difference Between Root User and Normal User


- Objective: Understand the distinction between the root user and normal users.
- Explanation: The root user has unrestricted access to all commands and files,
while normal users have limited permissions. This distinction helps protect the
system from accidental or malicious changes.

22. `sudo su -` - Switch to Root User


- Objective: Switch to the root user to perform administrative tasks.
- Command:
sudo su -
- Note: Use this command with caution, as the root user can make irreversible
changes to the system.

### Outcome:
By the end of this project, you will have practiced essential Linux commands in a
logical sequence, gaining a basic understanding of file system navigation, file
manipulation, system information retrieval, and user management. You will
also learn about the differences between root and normal users, and how to
switch to the root user when necessary.

### Project: Managing Software Packages with YUM and Git

#### Scenario:
You are setting up a development environment on a CentOS-based Linux server.
As part of this setup, you need to manage software packages using the YUM
package manager. Specifically, you'll be installing and configuring Git, a popular
version control system. This project will guide you through installing, updating,
and managing software packages with YUM, using Git as the primary example.

#### 1. Update System Packages

- Objective: Ensure that your system packages and YUM repositories are up to
date.
- Command:
sudo yum update -y
- Explanation: This command updates all installed packages to their latest
versions and refreshes the package index.

#### 2. Install Git

- Objective: Install Git using YUM.


- Command:
sudo yum install git -y
- Explanation: This command installs Git, along with any dependencies, from the
default YUM repositories.

#### 3. Verify Installation


- Objective: Confirm that Git has been installed successfully and check its
version.
- Command:
git --version
- Expected Output: The command should display the installed version of Git
(e.g., `git version 2.x.x`).

#### 4. Remove Git

- Objective: Uninstall Git using YUM to free up system resources.


- Command:
sudo yum remove git -y
- Explanation: This command removes Git from the system, along with any
dependencies that are no longer needed.

#### 5. Reinstall Git

- Objective: Reinstall Git to ensure you can easily manage packages with YUM.
- Command:
sudo yum install git -y
- Explanation: Reinstalls Git, showing how easy it is to manage software
packages with YUM.

#### 6. Enable and Configure a YUM Repository

- Objective: Add a third-party repository and install a package from it.


- Example: Adding the EPEL (Extra Packages for Enterprise Linux) repository.
- Command:
sudo yum install epel-release -y
- Explanation: The EPEL repository provides additional packages that are not
available in the default CentOS repositories.
- Install a package from EPEL:
sudo yum install htop -y
- Explanation: Installs `htop`, a system-monitoring tool, from the EPEL
repository.

### Additional Notes:

- List Installed Packages:


yum list installed
- Explanation: Displays all installed packages on the system.

- Search for Packages:


yum search git
- Explanation: Searches for packages related to Git in the YUM repositories.

- Get Package Information:


yum info git
- Explanation: Provides detailed information about the Git package, including
version, size, and description.

### Outcome:
By the end of this project, you will have gained practical experience in using
YUM to manage software packages on a CentOS-based system. You'll be able to
update your system, install and remove software packages like Git, manage
repositories, and verify installations. This knowledge is fundamental for
maintaining a well-functioning Linux environment.
DevOps Training
WhatsApp *91 8886740600*
Preethi Dovala

akshay alone

Home

Syllabus

Live Training

Video Tutorials

 Policies

Blog


< Back
Linux-Day-2
### Project: Managing Users and Groups in Linux

#### Scenario:
You are the system administrator responsible for managing user accounts and
groups on a Linux server. This project will guide you through a series of tasks
related to user and group management. You will add new users, modify their
group memberships, and ensure proper group management.

1. Add a New User


- Objective: Add a user named `john`.
- Command:
sudo useradd john
sudo passwd jhon
2. Check the User in the `/etc/passwd` File
- Objective: Verify that the user `john` has been added by checking the
`/etc/passwd` file.
- Command:
grep john /etc/passwd
- Explanation: The command will display the line from `/etc/passwd` where the
user `john` is listed, showing details such as username, user ID, group ID, home
directory, and shell.

3. Check the Group of a User (`tom`)


- Objective: Check which groups the user `tom` belongs to.
- Command:
groups tom
- Explanation: This command will list all the groups that `tom` is a member of.

4. Add a New Group


- Objective: Create a new group named `developers`.
- Command:
sudo groupadd developers
5. Change the Primary Group of the User
- Objective: Change the primary group of `john` to `developers`.
- Command:
sudo usermod -g developers john

6. Check the Group File (`/etc/group`)


- Objective: Verify the group membership of `john` in the `/etc/group` file.
- Command:
grep john /etc/group
7. Delete the Group and Check
- Objective: Delete the `developers` group and verify its removal.
- Command:
sudo groupdel developers
grep developers /etc/group
- Explanation: The first command deletes the group, and the second command
verifies that the group no longer exists in the `/etc/group` file.

8. Add User to Another Group


- Objective: Add `john` to a secondary group named `admins`.
- Command:
sudo usermod -aG admins john
- Explanation: This command appends the `admins` group to `john`'s list of
groups without changing his primary group.

9. Remove User from a Secondary Group


- Objective: Remove `john` from the `admins` group.
- Command:
sudo gpasswd -d john admins
10. Check the Groups of the Current User and Other Users
- Objective: Check which groups the current user and another user (`john`)
belong to.

- Command for Current User:


groups
- Command for Another User:
groups john
- Explanation: The `groups` command without any arguments shows the groups
of the current user, while specifying a username shows the groups that specific
user belongs to.

### Outcome:
By the end of this project, you will have practical experience in adding users,
managing their group memberships, and ensuring proper group management
on a Linux system. You will be able to verify these changes by checking the
relevant system files, such as `/etc/passwd` and `/etc/group`.

### Project: User, Group, File, and Folder Management with Permissions in
Linux

#### Scenario:
You are setting up a new project on a Linux server and need to manage users,
groups, files, and folders. You will create users and groups, set up files and
folders, manage permissions, and assign ownership to ensure that only
authorized users can access and modify the resources.

1. Create Users and Groups


- Objective: Create users `alice` and `bob`, and groups `developers` and `testers`.
- Commands:
sudo useradd alice
sudo useradd bob
sudo groupadd developers
sudo groupadd testers
2. Create a File and Folder, and List Permissions, Owners, and Groups
- Objective: Create a folder named `project` and a file named `report.txt` inside
it. List the permissions, owners, and groups.
- Commands:
mkdir project
touch project/report.txt
ls -ld project
ls -l project/report.txt
- Explanation: The `ls -ld project` command lists the directory details, and `ls -l
project/report.txt` lists the file details, including permissions, owner, and group.

3. Explain the Permissions of the File and Folder


- Objective: Understand the default permissions for the file `report.txt` and the
folder `project`.
- Explanation:
- Folder (`project`): Typically `drwxr-xr-x` (Owner can read/write/execute;
Group and Others can read/execute).
- File (`report.txt`): Typically `-rw-r--r--` (Owner can read/write; Group and
Others can only read).

4. Example Where Other Users Cannot Edit the File


- Objective: Demonstrate that `bob` cannot edit the file `report.txt` if he is not
the owner or does not have write permissions.
- Commands (as `bob`):
su - bob
echo "New content" >> project/report.txt
- Expected Output: `Permission denied` error.

5. Change Permission to Allow Others to Edit the File and Check the Permissions
- Objective: Modify the file permissions to allow others to edit `report.txt` and
verify the change.
- Commands:
sudo chmod o+w project/report.txt
ls -l project/report.txt
- Explanation: The permission should now include `w` for Others, i.e., `-rw-r--rw-
`.

6. Give an Example Where Others Can Edit the File


- Objective: Allow `bob` to edit the file after permission change.
- Commands (as `bob`):
su - bob
echo "New content" >> project/report.txt
- Expected Output: No error, and content is appended to `report.txt`.

7. Provide Execute Permission to the File


- Objective: Allow the file `report.txt` to be executed as a script.
- Command:
sudo chmod +x project/report.txt
ls -l project/report.txt
- Explanation: The file should now have execute permission, `-rwxr--rw-`.

8. Remove Previous Permissions Given to the File


- Objective: Remove write and execute permissions for Others.
- Command:
sudo chmod o-wx project/report.txt
ls -l project/report.txt
9. Assign and Remove Permissions for the Folder
- Objective: Modify permissions for the `project` folder, granting and then
removing write permission for the Group.
- Commands:
sudo chmod g+w project
ls -ld project
sudo chmod g-w project
ls -ld project
- Explanation: Group write permission will be added and then removed,
reflected in the folder permissions.

10. Assign and Remove Permissions Using the Numeric Method


- Objective: Use numeric values to change permissions for the file `report.txt`
and folder `project`.
- Commands:
sudo chmod 764 project/report.txt
sudo chmod 750 project
ls -l project/report.txt
ls -ld project
11. Change the Owner, Group, and Both Owner and Group of the File
- Objective: Change ownership of `report.txt` to `alice`, group to `developers`,
and both at the same time.
- Commands:
sudo chown alice project/report.txt
sudo chgrp developers project/report.txt
sudo chown alice:developers project/report.txt
ls -l project/report.txt
### Outcome:
By the end of this project, you will have hands-on experience with user and
group creation, file and folder permissions management, and ownership
modifications in a Linux environment. These skills are crucial for securely
managing resources in a multi-user system.

### Project: Working with Piping, Redirection, and Search in Linux

### Sample File: `sample.log`

Here is some example content you can use in `sample.log`:(Copy and paste)

2024-08-01 10:00:00 INFO System startup complete


2024-08-01 10:15:23 WARN Low disk space on /dev/sda1
2024-08-01 10:45:01 ERROR Failed to connect to database
2024-08-01 11:00:00 INFO Scheduled backup started
2024-08-01 11:05:42 ERROR Backup failed due to insufficient space
2024-08-01 11:10:10 INFO Backup retry in progress
2024-08-01 11:20:33 WARN Disk space is critically low on /dev/sda1
2024-08-01 11:30:55 INFO Backup completed successfully
2024-08-01 12:00:00 INFO System check completed
2024-08-01 12:30:25 WARN High memory usage detected
2024-08-01 12:45:00 ERROR Application crash detected
2024-08-01 13:00:00 INFO System health check passed

### Commands Using `sample.log`


1. Viewing the File Page by Page with `less`
- Command:
cat sample.log | less
2. Viewing the File Page by Page with `pg`
- Command:
cat sample.log | pg
3. Searching for `ERROR` Entries with `grep`
- Command:
grep "ERROR" sample.log
4. Redirecting `ERROR` Entries to a New File
- Command:
grep "ERROR" sample.log > errors.log
5. Appending `WARN` Entries to `errors.log`
- Command:
grep "WARN" sample.log >> errors.log
### Outcome:
After running these commands with the provided `sample.log` data, you will
have practiced viewing, searching, and managing log data effectively. You will
also have a new file `errors.log` containing all the `ERROR` and `WARN` entries.

### Project: Install and Setting Up an HTTP Server on EC2 with `httpd`

#### Scenario:
You are tasked with setting up a basic HTTP web server on an AWS EC2 instance.
You'll install the `httpd` package, configure the server to listen on port 80,
update security group rules to allow traffic on this port, host a simple HTML
page, and later change the listening port to 90.

#### 1. Install `httpd` Using `yum`


- Objective: Install the Apache HTTP server (`httpd`) on your EC2 instance.
- Command:
sudo yum update -y
sudo yum install httpd -y
#### 2. Start the HTTP Web Server and Enable It on Boot
- Objective: Start the `httpd` service and configure it to start on system boot.
- Commands:
sudo systemctl start httpd
sudo systemctl enable httpd
#### 3. Open Port 80 on EC2 Instance Inbound Rules
- Objective: Update the EC2 security group to allow inbound traffic on port 80.
- Steps:
- Navigate to the EC2 Management Console.
- Select your instance and go to the Security tab.
- Click on the security group associated with your instance.
- Click on Edit Inbound Rules and add a new rule:
- Type: HTTP
- Protocol: TCP
- Port Range: 80
- Source: 0.0.0.0/0 (for public access) or a specific IP range.
- Save the rules.

#### 4. Create a Sample HTML Page for Hosting


- Objective: Create a simple HTML page to verify that the web server is working.
- Commands:
echo "<html><body><h1>Welcome to My EC2 Web
Server!</h1></body></html>" | sudo tee /var/www/html/index.html
#### 5. Check the Status of `httpd`
- Objective: Ensure that the `httpd` service is running.
- Command:
sudo systemctl status httpd
#### 6. Verify Port 80 with `netstat`
- Objective: Confirm that the server is listening on port 80 using `netstat`.
- Command:
sudo netstat -tuln | grep :80
#### 7. Change the Listening Port to 90
- Objective: Modify the `httpd` configuration to listen on port 90 instead of 80.
- Commands:
sudo sed -i 's/Listen 80/Listen 90/' /etc/httpd/conf/httpd.conf
sudo systemctl restart httpd
#### 8. Update Inbound Rules on EC2 to Allow Port 90
- Objective: Adjust the security group to allow inbound traffic on port 90.
- Steps:
- Follow the same process as in Step 3, but this time add a rule for port 90.

#### 9. Verify the New Port with `netstat`


- Objective: Confirm that `httpd` is now listening on port 90.
- Command:
sudo netstat -tuln | grep :90
### Outcome:
By following these steps, you will have successfully set up an HTTP server on an
EC2 instance, hosted a sample HTML page, and managed the server's listening
port and security group settings.

DevOps Training
WhatsApp *91 8886740600*
Preethi Dovala

akshay alone

Home

Syllabus

Live Training

Video Tutorials

 Policies

Blog


< Back
Linux-Day-3
### Basic Concepts of UNIX Shell Scripting

#### 1. What is a Shell?


- A shell is a command-line interpreter that provides a user interface for
accessing the services of the operating system.
- Common shells include:
- Bash (Bourne Again SHell): The default shell on most Linux distributions.
- Sh (Bourne Shell): The original Unix shell.
- Csh (C Shell): A shell with C-like syntax.
- Ksh (Korn Shell): Combines features of Csh and Bash.

#### 2. Writing Your First Shell Script


- A shell script is simply a text file containing a series of commands.
- Creating a Shell Script:
- Use any text editor (e.g., `vim`, `nano`) to create a file with a `.sh` extension.
- Example: scriptname.sh
#!/bin/bash
echo "Hello, World!"
- The `#!/bin/bash` is called a shebang, which tells the system to use the Bash
shell to interpret the script.

- Making the Script Executable:


- Use the `chmod` command to make the script executable:
chmod +x scriptname.sh
- Execute the script:
./scriptname.sh
#### 3. Variables in Shell Scripting
- Defining Variables:
- Variables store data that can be used later in the script.
- Example:
#!/bin/bash
name="John"
echo "Hello, $name"
- Environment Variables:
- Predefined variables like `$HOME`, `$USER`, and `$PATH`.
- Access using the `$` sign.

#### 4. Comments in Shell Scripts


- Use the `#` symbol to add comments in your script. Comments are not
executed.
# This is a comment
echo "Hello, World!"
#### 5. Conditional Statements
- `if` Statement:
- Used to execute commands based on a condition.
- Example:
#!/bin/bash
if [ "$name" == "John" ]; then
echo "Hello, John!"
else
echo "You are not John."
fi
- Comparison Operators:
- `-eq` (equal), `-ne` (not equal), `-gt` (greater than), `-lt` (less than).
- Example:
if [ $num -gt 10 ]; then
echo "Number is greater than 10"
fi
#### 6. Loops in Shell Scripts
- `for` Loop:
- Iterates over a list of items.
- Example:
#!/bin/bash
for i in 1 2 3 4 5; do
echo "Number: $i"
done
- `while` Loop:
- Repeats commands as long as a condition is true.
- Example:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
#### 7. Functions in Shell Scripts
- Functions allow you to group commands and reuse them.
- Defining a Function:
#!/bin/bash
greet() {
echo "Hello, $1"
}
greet "Alice"
- Calling a Function:
- Use the function name followed by arguments if any.

#### 8. Input/Output in Shell Scripts


- Reading User Input:
- Use the `read` command to get input from the user.
- Example:
#!/bin/bash
echo "Enter your name: "
read name
echo "Hello, $name!"

- Redirecting Output:
- `>`: Redirects output to a file (overwrites if file exists).
- `>>`: Appends output to a file.
- Example:
echo "This is a test" > testfile.txt
echo "Appending text" >> testfile.txt
#### 9. Script Arguments
- You can pass arguments to your script, which can be accessed using `$1`, `$2`,
etc.
- Example:
#!/bin/bash
echo "First argument: $1"
echo "Second argument: $2"
- Run the script with arguments:
./scriptname.sh arg1 arg2
#### 10. Exit Status
- Every command returns an exit status (`0` for success, non-zero for failure).
- Example:
#!/bin/bash
ls /nonexistent
echo "Exit status: $?"

### Additional Resources


- Man Pages: Use the `man` command to get detailed information about
commands and their options. For example, `man bash`.
- Online Tutorials: Websites like [tutorialspoint]
(https://www.tutorialspoint.com/unix/shell_scripting.htm) and
[shell scripting guide](http://www.shellscript.sh)

### Practice Exercises

1. Create a Script to Print System Information:


- Write a script that prints the system's hostname, current date, and logged-in
users.

2. Create a Script with Conditional Logic:


- Write a script that takes a number as input and checks if it is positive, negative,
or zero.

3. Create a Script to Back Up Files:


- Write a script that copies all `.txt` files from one directory to another.

4. Write a Script with a Loop:


- Create a script that prints the first 10 natural numbers using a `for` loop.

5. Create a Script to Monitor Disk Usage:


- Write a script that checks the disk usage of the `/home` directory and sends an
alert if it exceeds 80%.

6. Write a Function to Greet Users:


- Write a function that takes a name as an argument and prints a greeting.

### Solutions for Practice Exercises

#### 1. Create a Script to Print System Information

#!/bin/bash

# Print system's hostname


echo "Hostname: $(hostname)"

# Print current date and time


echo "Date and Time: $(date)"
# Print currently logged-in users
echo "Logged-in Users:"
who

Print System Information:


- `hostname`: Fetches the system's hostname.
- `date`: Displays the current date and time.
- `who`: Lists all logged-in users.

#### 2. Create a Script with Conditional Logic

#!/bin/bash

# Prompt user for a number


echo "Enter a number: "
read num

# Check if the number is positive, negative, or zero


if [ $num -gt 0 ]; then
echo "The number is positive."
elif [ $num -lt 0 ]; then
echo "The number is negative."
else
echo "The number is zero."
fi

Conditional Logic:
- Uses `if`, `elif`, and `else` to check if a number is positive, negative, or zero.
- The script reads a number from the user and compares it using `-gt` (greater
than) and `-lt` (less than)
#### 3. Create a Script to Back Up Files

#!/bin/bash

# Source and destination directories


src_dir="/path/to/source_directory"
dest_dir="/path/to/backup_directory"

# Copy all .txt files from source to destination


cp $src_dir/*.txt $dest_dir/

# Print a message indicating the backup is complete


echo "Backup of .txt files complete."

File Backup:
- Uses `cp` to copy all `.txt` files from the source directory to the backup
directory.
- Make sure to replace `/path/to/source_directory` and
`/path/to/backup_directory` with actual paths.

#### 4. Write a Script with a Loop

#!/bin/bash

# Print the first 10 natural numbers using a for loop


for i in {1..10}; do
echo "Number: $i"
done
Looping with `for`:
- The `{1..10}` syntax generates a sequence from 1 to 10.
- The loop iterates over each number, printing it out.

#### 5. Create a Script to Monitor Disk Usage

#!/bin/bash

# Check disk usage of /home directory


disk_usage=$(df -h /home | awk 'NR==2 {print $5}' | sed 's/%//')

# Set the threshold to 80%


threshold=80

# Compare disk usage with threshold


if [ $disk_usage -gt $threshold ]; then
echo "Warning: Disk usage of /home directory is above $threshold%. Current
usage is $disk_usage%."
else
echo "Disk usage is within the limit. Current usage is $disk_usage%."
fi

Disk Usage Monitoring:


- `df -h /home`: Shows the disk usage of the `/home` directory.
- `awk 'NR==2 {print $5}'`: Extracts the usage percentage from the output.
- `sed 's/%//'`: Removes the `%` sign from the number.
- Compares the disk usage with a set threshold and prints a warning if it exceeds
80%.

#### 6. Write a Function to Greet Users


#!/bin/bash

# Define a function to greet users


greet_user() {
echo "Hello, $1! Welcome to the system."
}

# Call the function with a name as an argument


greet_user "Alice"

Greeting Function:
- Defines a function `greet_user` that takes a name as an argument and prints a
greeting.
- The function is then called with "Alice" as the argument.

DevOps Training
WhatsApp *91 8886740600*

Preethi Dovala
akshay alone


Home


Syllabus


Live Training


Video Tutorials

 Policies

Blog


< Jenkins Home

Jenkins Day -1
QUIZ
step-by-step guide for setting up Jenkins on an EC2 instance running Amazon Linux
2 and performing various tasks:

### Step 1: Set Up Jenkins on an EC2 Instance (Amazon Linux 2)

1. Launch an EC2 Instance:


- Go to the AWS Management Console.
- Launch a new EC2 instance.
- Choose an Amazon Machine Image (AMI) for Amazon Linux 2.
- Select an instance type (e.g., t2.micro for free tier).
- Configure instance details, add storage, and add tags as needed.
- Configure security group: Add rules to allow HTTP (port 80) and
custom TCP rule for Jenkins (port 8080).
- Review and launch the instance.
2. Connect to the EC2 Instance:
- Connect to your instance via SSH using the key pair you created.

3. Install Jenkins:
- Update the package index:

sudo yum update -y


```
- Install Java (Jenkins requires Java):

sudo yum install java -y


```
- Add Jenkins repository and key:

Follow the Jenkins official website


https://pkg.jenkins.io/redhat-stable/

- Install Jenkins:

sudo yum install jenkins -y


```
- Start Jenkins:

sudo systemctl start jenkins


```
- Enable Jenkins to start on boot:

sudo systemctl enable jenkins


```
### Step 2: Check the Jenkins Port

1. Verify Jenkins is Running:

sudo systemctl status jenkins


```

2. Check Jenkins Port:


- By default, Jenkins runs on port 8080. Verify by opening a
browser and navigating to:
```
http://<your-ec2-public-ip>:8080
```

### Step 3: Add the Port to Security Group

1. Update Security Group:


- Go to the AWS Management Console.
- Navigate to EC2 Dashboard > Instances.
- Select your instance and note the security group.
- Navigate to Security Groups under Network & Security.
- Select your security group and edit inbound rules.
- Add a custom TCP rule for port 8080.

### Step 4: Check the Home Directory

1. Locate Jenkins Home Directory:

echo $JENKINS_HOME
```
- Default location: `/var/lib/jenkins`
### Step 5: Post-Install Task

1. Unlock Jenkins:
- Get the initial admin password:

sudo cat /var/lib/jenkins/secrets/initialAdminPassword


```
- Use this password to unlock Jenkins via the web interface.

2. Install Suggested Plugins:


- Follow the setup wizard to install suggested plugins.

3. Create Admin User:


- Set up your admin user as prompted by the setup wizard.

### Step 6: Create a Freestyle Job

1. Create a New Freestyle Project:


- In Jenkins dashboard, click on "New Item".
- Enter an item name (e.g., "SampleProject").
- Select "Freestyle project" and click OK.

2. Configure the Job:


- In the project configuration page, add a simple build step:
- Under "Build", click "Add build step" and select "Execute shell".
- Enter a shell command, e.g., `echo "Hello, Jenkins!"`.
- Save the configuration.

### Step 7: Find the Workspace Location

1. Locate Workspace:
- The workspace for the job can be found at:

ls -l /var/lib/jenkins/jobs/
```

### Step 8: Check the Console Output

1. Run the Job and Check Output:


- Go to your project's page.
- Click "Build Now" to run the job.
- Click on the build number (e.g., #1) in the "Build History" on the
left.
- Click "Console Output" to view the job's output.

By following these steps, you'll have a Jenkins instance set up on an


EC2 instance running Amazon Linux 2, with the ability to create and
manage jobs, and access various Jenkins features.

### TOPIC: Procedure to Change Jenkins Port to 8081

1. Connect to Your EC2 Instance:


- Use SSH to connect to your EC2 instance.

ssh -i <your-key-pair.pem> ec2-user@<your-ec2-public-ip>


2. Open the Jenkins Service Configuration File:
- The configuration file for Jenkins is located at
`/lib/systemd/system/jenkins.service`.
sudo systemctl stop jenkins
sudo systemctl status jenkins
sudo vim /lib/systemd/system/jenkins.service

3. Find the Port Configuration:


- Look for the line that starts with
`Environment="JENKINS_PORT=8080"`. If it doesn't exist, you can
add it.

4. Change the Port Number:


- Modify or add the line to use port 8081 instead of 8080:
plaintext
Environment="JENKINS_PORT=8081"

5. Save and Exit the Editor:


- Save the changes and exit the text editor. If you're using `nano`,
you can do this by pressing `Ctrl+X`, then `Y`, and `Enter`.

6. Reload the Systemd Configuration:


- After making changes to the service file, reload the systemd
configuration to apply the changes:

sudo systemctl daemon-reload


7. Restart Jenkins:
- Restart the Jenkins service to apply the changes:

sudo systemctl restart jenkins

8. Update the Security Group:


- Go to the AWS Management Console.
- Navigate to EC2 Dashboard > Instances.
- Select your instance and note the security group.
- Navigate to Security Groups under Network & Security.
- Select your security group and edit inbound rules.
- Add a custom TCP rule for port 8081:
- Type: Custom TCP
- Port Range: 8081
- Source: 0.0.0.0/0 (or restrict to your IP range)

9. Verify the Port Change:


- Open a web browser and navigate to:

http://<your-ec2-public-ip>:8081

- Ensure that Jenkins is now accessible on port 8081.

### Summary

1. Connect to your EC2 instance.


2. Open and edit `/lib/systemd/system/jenkins.service`.
3. Add or modify `Environment="JENKINS_PORT=8081"`.
4. Reload the systemd configuration with `sudo systemctl daemon-
reload`.
5. Restart Jenkins with `sudo systemctl restart jenkins`.
6. Update your security group to allow inbound traffic on port 8081.
7. Verify Jenkins is accessible on port 8081.

By following these steps, you will successfully change the default


port of Jenkins to 8081.

step-by-step guide to creating users in Jenkins and configuring


matrix-based authorization for fine-grained access control.

#### 1. Create Users in Jenkins

1. Log in to Jenkins:
- Open your web browser and go to your Jenkins instance (e.g.,
`http://<your-ec2-public-ip>:8080`).

2. Navigate to Manage Jenkins:


- From the Jenkins dashboard, click on "Manage Jenkins" on the left-
hand side.

3. Go to Manage Users:
- Click on "Manage Users."

4. Create a New User:


- Click on "Create User."
- Fill out the form with the user’s information:
- Username
- Password
- Confirm password
- Full name
- Email address
- Click "Create User."

Repeat this process for each user you want to create.

#### 2. Configure Matrix-Based Authorization

1. Navigate to Manage Jenkins:


- From the Jenkins dashboard, click on "Manage Jenkins" on the left-
hand side.

2. Go to Configure Global Security:


- Click on "Configure Global Security."

3. Enable Security:
- Check "Enable security."

4. Select Jenkins Own User Database:


- Under "Security Realm," select "Jenkins’ own user database."
- Check "Allow users to sign up" if you want users to create their
own accounts.

5. Set Authorization to Matrix-Based Security:


- Under "Authorization," select "Matrix-based security."
6. Configure Permissions:
- Add the users you created by typing their usernames and clicking
"Add user."
- Assign permissions by checking the boxes for each user.
Permissions include:
- Overall: Administer, Read, etc.
- Job: Build, Cancel, Configure, Read, etc.
- Run: Delete, Update, etc.
- View: Read, Configure, etc.
- SCM: Tag
- Here’s an example configuration:
- Admin User:
- Overall: Administer, Read
- Job: All permissions
- Run: All permissions
- View: All permissions
- SCM: All permissions
- Regular User:
- Overall: Read
- Job: Build, Read
- Run: Update
- View: Read
- SCM: None

7. Save the Configuration:


- Scroll down and click "Save" to apply the changes.

#### 3. Verify the Configuration

1. Log out:
- Log out of Jenkins to test the new user permissions.

2. Log in as a New User:


- Log in using one of the new user accounts you created.
- Verify that the permissions are applied correctly (e.g., a regular
user should not have admin privileges).
3. Test Different Users:
- Log in with different user accounts and test their access levels to
ensure the matrix-based authorization is working as expected.

### Summary

1. Create users in Jenkins by navigating to "Manage Jenkins" >


"Manage Users" > "Create User."
2. Configure matrix-based authorization by navigating to "Manage
Jenkins" > "Configure Global Security" > "Matrix-based security."
3. Assign appropriate permissions to each user.
4. Verify the configuration by logging in as different users and
testing their permissions.

By following these steps, you can practice creating users in Jenkins


and configuring matrix-based authorization for fine-grained access
control.

project for practicing matrix-based authorization for a regular user, follow these
steps:

Step 1: Create Users and Configure Matrix-Based Authorization

Create a Regular User:

Follow the steps mentioned earlier to create a new user (e.g.,


regularuser).
Configure Matrix-Based Authorization:
Go to "Manage Jenkins" > "Configure Global Security."
Under "Authorization," select "Matrix-based security."
Add the regula ruser by typing the username and clicking "Add
user."
Assign the following permissions to regular user:
Overall:
Read
Job:
Read
Build
View:
Read

Step 2: Create a Freestyle Project


Create a New Freestyle Project:

Log in as the admin user.


Click on "New Item" from the Jenkins dashboard.
Enter a project name (e.g., SampleProject).
Select "Freestyle project" and click "OK."
Configure the Project:

In the project configuration page, add a build step:


Under "Build," click "Add build step" and select "Execute shell."
Enter a shell command, e.g., echo "Hello, Jenkins!"
Save the configuration.
Step 3: Verification Tasks for Regular User

Task 1: Verify Limited Permissions


Objective: Ensure the regular user can view and build the project
but cannot perform administrative actions.

Steps:

Log in as the regular user.


Navigate to the SampleProject from the dashboard.
Verify that regular user can see the project details.
Attempt to access "Configure" for the project. The user should
receive a permission denied message.
Ensure that regular user cannot delete the project.

Task 2: Build the Project and Check Output


Objective: Ensure the regular user can trigger a build and view the
console output.

Steps:
While still logged in as regular user, go to the SampleProject.
Click "Build Now" to start a build.
Wait for the build to complete.
In the "Build History," click on the build number.
Ensure that regular user can view the "Console Output" and see the
message Hello, Jenkins!.

By completing this sample project and the verification tasks, you


will gain hands-on experience with matrix-based authorization in
Jenkins and understand how to manage and verify user permissions
effectively.

DevOps Training
WhatsApp *91 8886740600*

Preethi Dovala
akshay alone

Home


Syllabus


Live Training


Video Tutorials

 Policies

Blog


< Jenkins Home

Jenkins-Day-2
QUIZ
### Project Scenario: Configuring Jenkins with Role-Based
Authorization with Global Roles and Validating with a Sample Job

Objective: Set up Jenkins for a software development team,


implementing a role-based authorization strategy with global roles.
This project will include installing necessary plugins, defining roles,
creating users, setting up a sample project and job, and validating
the roles with the job.

### Step 1: Install Required Plugins


Scenario: To manage permissions effectively through roles, the
"Role-Based Authorization Strategy" plugin must be installed.

1. Access Jenkins Dashboard:


- Log in to Jenkins as an administrator.

2. Navigate to Plugin Manager:


- Go to `Manage Jenkins` > `Manage Plugins`.

3. Install "Role-Based Authorization Strategy" Plugin:


- Click on the `Available` tab.
- Search for `Role-Based Authorization Strategy`.
- Check the box next to the plugin and click `Install without restart`.
- Wait for the installation to complete.

### Step 2: Configure Role-Based Authorization Strategy with


Global Roles

Scenario: Define global roles for different levels of access within


Jenkins: `Admin`, `Developer`, and `Viewer`.

1. Enable Role-Based Authorization:


- Go to `Manage Jenkins` > `Security`.
- In the `Authorization` section, select `Role-Based Strategy`.
- Click `Save` to apply the changes.

2. Define Global Roles:


- Go to `Manage Jenkins` > `Manage and Assign Roles` > `Manage
Roles`.
- In the `Global roles` section, create the following roles:
- Admin: Full access to all Jenkins features, including system
settings and job management. Check all permissions.
- Developer: Permissions to create, modify, and run jobs but no
access to system settings. Check permissions such as `Job Create`,
`Job Configure`, `Job Delete`, `Job Build`, etc.
- Viewer: Read-only access, allowing users to view job statuses and
build results. Check permissions like `Job Read`, `Overall Read`.
### Step 3: Create Users and Assign Global Roles

Scenario: Assign specific users to the roles created based on their


responsibilities within the team.

1. Create Users:
- Go to `Manage Jenkins` > `Manage Users`.
- Create the following users:
- admin_user: Administrator with full control.
- dev_user1 and dev_user2: Developers who will manage and run
jobs.
- viewer_user: A user with read-only access.

2. Assign Roles to Users:


- Go to `Manage Jenkins` > `Manage and Assign Roles` > `Assign
Roles`.
- In the `Global roles` section, assign users to their respective roles:
- admin_user: Assign to the `Admin` role.
- dev_user1 and dev_user2: Assign to the `Developer` role.
- viewer_user: Assign to the `Viewer` role.

### Step 4: Create a Sample Project and Job

Scenario: Create a sample project with a basic job to validate the


roles. The job will be a simple Jenkins pipeline that prints "Hello,
Jenkins!"

1. Create a New Project:


- Go to the Jenkins dashboard.
- Click `New Item` and name it `Sample_Project`.
- Choose `Freestyle project` and click `OK`.

2. Configure the Job:


- In the `Build` section, click `Add build step`.
- Select `Execute shell`.
- In the command box, enter:
echo "Hello, Jenkins!"
3. Run the Job:
- From the project dashboard, click `Build Now` to run the job.

### Step 5: Validation

Scenario: Validate that the roles and permissions are set correctly
by testing with each user account.

1. Validate Admin Role:


- Log in as `admin_user`.
- Confirm that this user can access and modify all Jenkins settings,
including creating, configuring, and running jobs.

2. Validate Developer Role:


- Log in as `dev_user1`.
- Ensure that this user can create, configure, and run jobs in
`Sample_Project` but cannot modify global Jenkins settings.

3. Validate Viewer Role:


- Log in as `viewer_user`.
- Confirm that this user can only view the job and its build results in
`Sample_Project` without the ability to make any changes.

### Conclusion

This project scenario ensures that Jenkins is set up with a role-


based authorization strategy tailored to the needs of your software
development team. By following these steps, you can effectively
manage permissions and validate the setup using a sample job,
ensuring a secure and well-organized Jenkins environment.

### Project Scenario: Creating and Assigning Item Roles in Jenkins


with a Validation Job

Objective: Set up Jenkins with item roles to manage access to


specific projects and jobs. The process includes creating users,
defining and assigning item roles, setting up a sample project and
job, and validating the roles with the job.

### Step 1: Set Up Jenkins and Enable Role-Based Authorization

Scenario: To control access to specific projects and jobs within


Jenkins, you’ll implement item roles as part of the role-based
authorization strategy.

1. Access Jenkins Dashboard:


- Log in to Jenkins as an administrator.

2. Navigate to Security Configuration:


- Go to `Manage Jenkins` > `Security`.

3. Enable Role-Based Authorization:


- In the `Authorization` section, select `Role-Based Strategy`.
- Click `Save` to apply the changes.

### Step 2: Create Users

Scenario: Create users who will be assigned different item roles


based on their responsibilities.

1. Create Users:
- Go to `Manage Jenkins` > `Manage Users`.
- Create the following users:
- pm_user: A project manager responsible for managing specific
projects.
- dev_user1 and dev_user2: Developers responsible for working on
specific projects.

### Step 3: Install the Role-Based Authorization Strategy Plugin (If


Not Already Installed)
Scenario: Ensure that the "Role-Based Authorization Strategy"
plugin is installed to manage item roles.

1. Navigate to Plugin Manager:


- Go to `Manage Jenkins` > `Manage Plugins`.

2. Install "Role-Based Authorization Strategy" Plugin:


- Click on the `Available` tab.
- Search for `Role-Based Authorization Strategy`.
- Check the box next to the plugin and click `Install without restart`.
- Wait for the installation to complete.

### Step 4: Create and Define Item Roles

Scenario: Define item roles to control access to specific jobs or


projects within Jenkins.

1. Navigate to Role Management:


- Go to `Manage Jenkins` > `Manage and Assign Roles` > `Manage
Roles`.

2. Create Item Roles:


- In the `Item roles` section, define roles such as:
- Project_Manager: Full permissions to configure, build, and delete
specific projects.
- Developer: Permissions to build and configure jobs but not delete
them.

3. Assign Patterns to Item Roles:


- Define the scope of each role using patterns:
- Assign the `Project_Manager` role with the pattern `Project_*` to
give `pm_user` control over items prefixed with `Project_`.
- Assign the `Developer` role with the pattern `Project_*` to give
`dev_user1` and `dev_user2` restricted control (build and configure)
over the same items.

### Step 5: Create a Sample Project and Job


Scenario: Create a sample project with a job to validate the item
roles.

1. Create a New Project:


- Go to the Jenkins dashboard.
- Click `New Item` and name it `Project_Sample`.
- Choose `Freestyle project` and click `OK`.

2. Configure the Job:


- In the `Build` section, click `Add build step`.
- Select `Execute shell`.
- In the command box, enter:
echo "Building Project_Sample"
- Click `Save`.

3. Run the Job:


- From the project dashboard, click `Build Now` to run the job.

### Step 6: Assign Users to Item Roles

Scenario: Assign specific users to the item roles based on their


responsibilities.

1. Assign Roles to Users:


- Go to `Manage Jenkins` > `Manage and Assign Roles` > `Assign
Roles`.
- In the `Item roles` section, assign users to their respective roles:
- pm_user: Assign to the `Project_Manager` role for `Project_*`
items.
- dev_user1 and dev_user2: Assign to the `Developer` role for
`Project_*` items.

### Step 7: Validation

Scenario: Validate the setup by testing access and permissions for


each user account.
1. Validate Project Manager Role:
- Log in as `pm_user`.
- Confirm that this user can configure, build, and delete the
`Project_Sample` job.

2. Validate Developer Role:


- Log in as `dev_user1`.
- Ensure that this user can configure and build the `Project_Sample`
job but cannot delete it.

### Conclusion

This project scenario ensures that Jenkins is set up with item roles
tailored to the needs of your team. By following these steps, you
can effectively manage permissions and validate the setup using a
sample job, ensuring a secure and well-organized Jenkins
environment.

### Project Scenario: Configuring Jenkins with Project-Based Matrix


Authorization Strategy and Build Triggers

Objective: Set up Jenkins using a project-based matrix authorization


strategy. This includes creating users, defining permissions at the
project level, setting up a sample project with a job, and configuring
the job to build periodically using build triggers.

### Step 1: Set Up Jenkins and Enable Project-Based Matrix


Authorization Strategy

Scenario: You want to manage access to specific projects and jobs


within Jenkins at a more granular level using a project-based matrix
authorization strategy.

1. Access Jenkins Dashboard:


- Log in to Jenkins as an administrator.
2. Navigate to Security Configuration:
- Go to `Manage Jenkins` > `Configure Global Security`.

3. Enable Project-Based Matrix Authorization Strategy:


- In the `Authorization` section, select `Project-based Matrix
Authorization Strategy`.
- Click `Save` to apply the changes.

### Step 2: Create Users

Scenario: Create users who will be assigned different permissions


on specific projects.

1. Create Users:
- Go to `Manage Jenkins` > `Manage Users`.
- Create the following users:
- admin_user: Administrator with full control over all projects and
settings.
- pm_user: Project Manager with control over specific projects.
- dev_user1 and dev_user2: Developers with limited permissions to
work on specific projects.

### Step 3: Create a New Project

Scenario: Create a sample project in Jenkins where different users


will have different levels of access.

1. Create a New Project:


- Go to the Jenkins dashboard.
- Click `New Item`, name it `Sample_Project`, and select `Freestyle
project`.
- Click `OK`.

2. Configure Project-Based Matrix Authorization for the Project:


- Within the project configuration page, scroll down to the `Build
Triggers` section.
- Check the box for `Enable project-based security`.
- Configure the matrix permissions for this project:
- admin_user: Assign all permissions (check all boxes).
- pm_user: Assign permissions for configuring the project, running
builds, and viewing build results (`Job Configure`, `Job Build`, `Job
Read`).
- dev_user1 and dev_user2: Assign permissions for building the
project and viewing build results (`Job Build`, `Job Read`).

3. Save the Configuration:


- Click `Save` to apply the configuration.

### Step 4: Configure a Sample Job with Build Triggers

Scenario: Set up a job within the `Sample_Project` that will build


periodically based on a schedule.

1. Configure the Job:


- In the `Build Triggers` section of the project configuration, check
the box for `Build periodically`.
- Enter a cron expression to schedule the build. For example, to
build every 2 minutes :
H */2 * * * *
- Add a build step by clicking `Add build step` and selecting
`Execute shell`.
- In the command box, enter:
echo "Building Sample_Project"

2. Save and Trigger the Job:


- Click `Save` to apply the configuration.
- The job will now run automatically based on the defined schedule.

### Step 5: Validation

Scenario: Validate that the users have the correct permissions and
that the job builds according to the schedule.

1. Validate Admin Role:


- Log in as `admin_user`.
- Confirm full access to configure, build, and delete the
`Sample_Project`.

2. Validate Project Manager Role:


- Log in as `pm_user`.
- Ensure this user can configure and build the `Sample_Project`, but
cannot delete it.

3. Validate Developer Roles:


- Log in as `dev_user1`.
- Ensure this user can only build and view the results of the
`Sample_Project`.

4. Check Build Triggers:


- Wait for the scheduled time or manually trigger the build to ensure
it runs as configured.

### Conclusion

This project scenario provides a structured approach to setting up


Jenkins with a project-based matrix authorization strategy. By
following these steps, you can manage permissions at a granular
level, ensuring that each user has the appropriate access. The job's
periodic build configuration helps automate the build process,
ensuring continuous integration without manual intervention.

### Project Scenario: Configuring Jenkins with Poll SCM Build


Triggers

Objective: Set up a Jenkins project that automatically checks for


changes in a source code repository using Poll SCM and triggers
builds when changes are detected. This scenario includes creating
the project, configuring jobs, and setting up Poll SCM build triggers.

### Step 1: Set Up Jenkins Project


Scenario: Create a new project in Jenkins that will include a job with
a Poll SCM trigger.

1. Access Jenkins Dashboard:


- Log in to Jenkins as an administrator.

2. Create a New Project:


- From the Jenkins dashboard, click `New Item`.
- Enter the project name as `Poll_SCM_Project`.
- Select `Freestyle project` and click `OK`.

### Step 2: Configure Source Code Management (SCM)

Scenario: Configure the project to pull code from a source code


management (SCM) repository.

1. Configure SCM:
- On the project configuration page, scroll down to the `Source Code
Management` section.
- Select the appropriate SCM system (e.g., `Git`).
- Enter the repository URL (e.g.,
`https://github.com/your-repo/sample-project.git`).
- Add credentials if necessary for accessing the repository.
- Specify the branch to build (e.g., `*/main`).

### Step 3: Set Up Poll SCM Build Trigger

Scenario: Configure Jenkins to automatically poll the SCM repository


for changes and trigger builds when changes are detected.

1. Configure Poll SCM Trigger:


- Scroll down to the `Build Triggers` section.
- Check the `Poll SCM` option.
- Enter a cron expression to define the polling schedule. For
example, to poll every 5 minutes:
*/5 * * * *
- This means Jenkins will check the repository every 5 minutes and
trigger a build if there are changes.

### Step 4: Add a Build Step

Scenario: Set up a simple build step to validate the build process.

1. Configure the Build Step:


- In the `Build` section, click `Add build step` and select `Execute
shell`.
- In the command box, enter:
echo "Building Poll_SCM_Project"
- This is a placeholder command that simply prints a message
during the build.

### Step 5: Save and Build

Scenario: Save the project configuration and ensure that the job
builds when changes are detected in the SCM.

1. Save the Configuration:


- Scroll down and click `Save` to apply the project configuration.

2. Trigger a Manual Build (Optional):


- To test the setup, you can manually trigger a build by clicking
`Build Now` from the project dashboard.

### Step 6: Validate Poll SCM Trigger

Scenario: Ensure that the Poll SCM trigger works as expected.

#### Scenario
In this project, you'll create a new GitHub repository, clone it to an
EC2 instance, create a file locally, and push the file to the remote
repository on GitHub. This scenario simulates a typical workflow for
managing code using Git and GitHub on a cloud server.
#### 1. Create a GitHub Repository
- Go to GitHub: Log in to your GitHub account.
- Create a New Repository:
- Click on the "New" button to create a new repository.
- Enter a repository name, for example, `ec2-git-demo`.
- You can add a description if you like.
- Choose "Public" or "Private" based on your preference.
- Do not initialize the repository with a README, `.gitignore`, or
license for this scenario.
- Click "Create repository".

#### 2. Launch an EC2 Instance


- Open AWS Management Console: Navigate to the EC2 dashboard.
- Launch a New Instance:
- Choose an Amazon Linux 2 AMI (or any Linux distribution you
prefer).
- Select an instance type, such as `t2.micro`.
- Configure security groups to allow SSH access.
- Launch the instance and connect to it using SSH.

#### 3. Install Git on the EC2 Instance


- Connect to Your EC2 Instance via SSH:
ssh -i /path/to/your-key.pem ec2-user@your-ec2-instance-public-dns
- Install Git:
sudo yum update -y
sudo yum install git -y
- Verify Git Installation:
git --version

#### 4. Clone the GitHub Repository to EC2


- Clone the Repository:
- Navigate to the GitHub repository you created earlier and copy the
HTTPS clone URL.
- In the terminal, clone the repository:
git clone https://github.com/your-username/ec2-git-demo.git
- Navigate to the Cloned Repository:
cd ec2-git-demo

#### 5. Check the Name of the Remote Repository


- Check the Remote Repository:
- Use the following command to list the remote repositories
associated with your local Git repository:
git remote -v
- You should see the URL of the GitHub repository listed as `origin`.

#### 6. Create a File Locally


- Create a New File:
- Use the following command to create a new file in the repository:
echo "Hello from EC2!" > hello.txt
- Add the File to the Staging Area:
git add hello.txt
- Commit the File:
git commit -m "Add hello.txt file"

#### 7. Push the File to the Remote Repository


- Push the Changes:
- Push the committed changes to the GitHub repository:
git push origin main

#### 8. Verify the Changes on GitHub


- Go to GitHub:
- Navigate to your repository on GitHub.
- You should see the `hello.txt` file in the repository.

1. Validate SCM Polling:

- Commit a change to the source code repository used in the project.

- Wait for the next polling interval (e.g., 5 minutes) and check if
Jenkins detects the change and automatically triggers a build.

2. Check Build Results:

- Once a build is triggered, check the build results on the project


dashboard to ensure everything is working correctly.
### Conclusion

By following these steps, you have successfully set up a Jenkins


project with Poll SCM build triggers. The project is configured to
automatically check for changes in the source code repository and
trigger builds as needed, ensuring continuous integration. This
setup helps streamline the development process by automating
builds based on code changes.

Poll SCM and Webhook are both mechanisms used to trigger


automated builds in Jenkins based on changes in a source code
repository, but they operate differently and are suited for different
scenarios. Here's a breakdown of the differences between the two:

### 1. Trigger Mechanism


- Poll SCM:
- Jenkins periodically checks (polls) the source code repository at defined
intervals (e.g., every 5 minutes) to see if there have been any changes.
- If changes are detected, Jenkins triggers a build.
- The polling schedule is defined using a cron-like expression in Jenkins.

- Webhook:
- A webhook is a push mechanism where the source code repository notifies
Jenkins immediately whenever a change occurs.
- The repository sends an HTTP POST request to Jenkins with details about
the change (e.g., a commit).
- Jenkins then triggers a build based on this notification.

### 2. Resource Usage


- Poll SCM:
- Polling can be resource-intensive, especially if there are many repositories
or the polling interval is short.
- Jenkins repeatedly checks the repository even if no changes have occurred,
which can lead to unnecessary load on both Jenkins and the repository
server.

- Webhook:
- Webhooks are more efficient because they only trigger Jenkins when there
is a change in the repository.
- No continuous checking is required, reducing the load on both Jenkins and
the repository.

### 3. Real-time Response


- Poll SCM:
- Not real-time. There is a delay between when a change occurs and when
Jenkins detects it, depending on the polling frequency.
- If the polling interval is set to a longer duration (e.g., once an hour), there
could be significant delays in starting builds.

- Webhook:
- Real-time. Jenkins responds almost immediately after a change is pushed to
the repository.
- This is ideal for scenarios where fast feedback is critical.

### 4. Configuration Complexity


- Poll SCM:
- Simpler to set up within Jenkins, especially if the repository doesn't support
webhooks or if the network setup complicates webhook configuration.
- Requires only the configuration of a polling schedule within Jenkins.

- Webhook:
- Requires configuring the repository to send webhook notifications to
Jenkins.
- Additional setup may be needed for security (e.g., tokens, firewalls) to allow
the repository to communicate with Jenkins.

### 5. Use Cases


- Poll SCM:
- Suitable for environments where webhook support is unavailable or where
network constraints prevent the use of webhooks.
- Useful for repositories that are less frequently updated or where the delay
in build triggering is acceptable.

- Webhook:
- Ideal for environments where fast, real-time build triggering is needed.
- Preferred for repositories with frequent updates, as it reduces unnecessary
load and provides immediate feedback.
### Summary
- Poll SCM involves Jenkins checking the repository at regular intervals, which
can be resource-intensive and cause delays in build triggering.
- Webhooks allow the repository to notify Jenkins immediately when changes
occur, leading to more efficient and real-time build triggers.

In general, webhooks are preferred for modern CI/CD pipelines due to their
efficiency and immediacy, while Poll SCM remains a fallback option for
environments where webhooks aren't feasible.

### Project Scenario: Configuring Jenkins with Webhook Build


Triggers

Objective: Set up a Jenkins project that automatically triggers builds


using a webhook from a GitHub repository. This scenario will cover
creating the project, configuring jobs, setting up the webhook, and
validating the setup.

### Step 1: Set Up Jenkins Project

Scenario: Create a new Jenkins project that will be triggered by a


webhook when changes are pushed to a GitHub repository.

1. Access Jenkins Dashboard:


- Log in to Jenkins as an administrator.

2. Create a New Project:


- From the Jenkins dashboard, click `New Item`.
- Enter the project name as `Webhook_Project`.
- Select `Freestyle project` and click `OK`.

### Step 2: Configure Source Code Management (SCM)


Scenario: Configure the project to pull code from a GitHub
repository.

1. Configure SCM:
- On the project configuration page, scroll down to the `Source Code
Management` section.
- Select `Git`.
- Enter the repository URL (e.g.,
`https://github.com/your-repo/sample-project.git`).
- Add credentials if necessary for accessing the repository.
- Specify the branch to build (e.g., `*/main`).
- under Build Triggers select "GitHub hook trigger for GITScm
polling"

### Step 3: Set Up Webhook in GitHub

Scenario: Configure a webhook in the GitHub repository to notify


Jenkins whenever changes are pushed.

1. Access Your GitHub Repository:


- Go to your GitHub repository where you want to set up the
webhook.

2. Navigate to Webhooks:
- Click on `Settings` in the repository.
- On the left sidebar, select `Webhooks`.

3. Add a New Webhook:


- Click `Add webhook`.
- In the `Payload URL`, enter the Jenkins webhook URL. This usually
looks like:
http://<jenkins-server>/github-webhook/
Replace `<jenkins-server>` with your Jenkins server’s URL.

- Set the `Content type` to `application/json`.


- Choose `Just the push event` under `Which events would you like
to trigger this webhook?`.
- Click `Add webhook` to save.

### Step 4: Add a Build Step

Scenario: Set up a simple build step to validate the build process.

1. Configure the Build Step:


- In the `Build` section of the Jenkins project configuration, click
`Add build step` and select `Execute shell`.
- In the command box, enter:
echo "Building Webhook_Project"
2. Save the Configuration:
- Scroll down and click `Save` to apply the project configuration.

### Step 5: Validate Webhook Configuration

Scenario: Test and validate that the webhook is correctly set up and
that Jenkins triggers builds when changes are pushed to the GitHub
repository.

#### 1. Create a GitHub Repository

- Go to GitHub: Log in to your GitHub account.

- Create a New Repository:

- Click on the "New" button to create a new repository.

- Enter a repository name, for example, `ec2-git-demo`.

- You can add a description if you like.


- Choose "Public" or "Private" based on your preference.

- Do not initialize the repository with a README, `.gitignore`, or


license for this scenario.

- Click "Create repository".

#### 2. Launch an EC2 Instance

- Open AWS Management Console: Navigate to the EC2 dashboard.

- Launch a New Instance:

- Choose an Amazon Linux 2 AMI (or any Linux distribution you


prefer).

- Select an instance type, such as `t2.micro`.

- Configure security groups to allow SSH access.

- Launch the instance and connect to it using SSH.

#### 3. Install Git on the EC2 Instance

- Connect to Your EC2 Instance via SSH:

ssh -i /path/to/your-key.pem ec2-user@your-ec2-instance-public-dns

- Install Git:

sudo yum update -y


sudo yum install git -y

- Verify Git Installation:

git --version

#### 4. Clone the GitHub Repository to EC2

- Clone the Repository:

- Navigate to the GitHub repository you created earlier and copy the
HTTPS clone URL.

- In the terminal, clone the repository:

git clone https://github.com/your-username/ec2-git-demo.git

- Navigate to the Cloned Repository:

cd ec2-git-demo

#### 5. Check the Name of the Remote Repository

- Check the Remote Repository:

- Use the following command to list the remote repositories


associated with your local Git repository:

git remote -v
- You should see the URL of the GitHub repository listed as `origin`.

#### 6. Create a File Locally

- Create a New File:

- Use the following command to create a new file in the repository:

echo "Hello from EC2!" > hello.txt

- Add the File to the Staging Area:


git add hello.txt

- Commit the File:


git commit -m "Add hello.txt file"

#### 7. Push the File to the Remote Repository

- Push the Changes:

- Push the committed changes to the GitHub repository:


git push origin main
#### 8. Verify the Changes on GitHub

- Go to GitHub:

- Navigate to your repository on GitHub.

- You should see the `hello.txt` file in the repository.

1. Push a Change to GitHub:


- Make a small change to a file in your GitHub repository and commit
the change.
- Push the changes to the repository.

2. Check Jenkins for Build Trigger:


- Go to the Jenkins dashboard and navigate to the
`Webhook_Project`.
- Check if a new build was automatically triggered after the push to
GitHub.

3. Review the Build Output:


- Once the build is complete, click on the build number and check
the console output.
- Ensure the message "Building Webhook_Project" appears,
indicating that the build step was executed.

### Conclusion

This project scenario demonstrates how to set up a Jenkins project


with webhook-based build triggers from a GitHub repository. The
setup allows Jenkins to automatically trigger builds whenever
changes are pushed to the repository, providing a real-time CI/CD
pipeline. Validation steps ensure that the webhook and build
process are functioning correctly, ensuring a reliable and efficient
development workflow.

Jenkins-Day-3
QUIZ
### Installing Maven with YUM, Compatible Java Version, and
Configuring JAVA_HOME on Amazon Linux 2 EC2

#### Scenario Overview


You are setting up a Java development environment on an Amazon
Linux 2 EC2 instance. The setup involves installing a compatible
version of Java and Apache Maven using YUM, followed by
configuring the `JAVA_HOME` environment variable to ensure Maven
can locate Java.

1. Launch and Access the EC2 Instance

Step 1.1: Launch an EC2 Instance


- In the AWS Management Console, launch an EC2 instance using the
Amazon Linux 2 AMI.
- Ensure the security group is configured to allow SSH access (port
22).

Step 1.2: Connect to the EC2 Instance


- Use SSH to connect to your EC2 instance:
ssh -i /path/to/your-key.pem ec2-user@your-ec2-public-dns
2. Install a Compatible Java Version

Step 2.1: Update the System Packages


- Start by updating the YUM package manager to ensure all
packages are up to date:
sudo yum update -y
Step 2.2: Install OpenJDK
- Install OpenJDK 11, which is a widely used version compatible with
most Maven projects:
sudo amazon-linux-extras install java-openjdk11 -y
Step 2.3: Verify Java Installation
- Verify the installation by checking the Java version:
java -version
You should see output similar to `openjdk version "11.x.x"`.

3. Install Apache Maven Using YUM

Step 3.1: Install Maven


- Install Apache Maven directly from the default repositories:
sudo yum install maven -y
Step 3.2: Verify Maven Installation
- Check if Maven is installed correctly:
mvn -version
The output should display the Maven version along with the Java
version it's using.

4. Configure the JAVA_HOME Environment Variable

Step 4.1: Locate the Java Installation Path


- Find the path where Java is installed:
readlink -f $(which java) | sed "s:bin/java::"

Step 4.2: Set the JAVA_HOME Variable


- Open the `.bash_profile` or `.bashrc` file to add the `JAVA_HOME`
environment variable:
sudo vim ~/.bash_profile
- Add the following line at the end of the file:
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-<version>
export PATH=$JAVA_HOME/bin:$PATH
Replace `<version>` with the correct version directory name from
Step 4.1.

Step 4.3: Apply the Changes


- Apply the changes to the current session:
source ~/.bash_profile

Step 4.4: Verify JAVA_HOME Configuration


- Confirm that `JAVA_HOME` is set correctly:
echo $JAVA_HOME
The output should show the path to your Java installation.

#### Conclusion
You have successfully set up a Java development environment on an
Amazon Linux 2 EC2 instance by installing a compatible Java
version, installing Maven using YUM, and configuring the
`JAVA_HOME` environment variable. This setup ensures that Maven
can compile and build Java applications on your EC2 instance.

### Simple Project: Cloning a GitHub Repository, Compiling, Unit


Testing, and Packaging on Amazon Linux 2 EC2

#### Scenario
You are tasked with cloning a Java-based project from a GitHub
repository to your local machine, compiling the code, running unit
tests, and packaging the application. The project is hosted at
`https://github.com/preethid/addressbook.git`.

1. Launch and Access the EC2 Instance

Step 1.1: Launch an EC2 Instance


- Use the AWS Management Console to launch an EC2 instance with
the Amazon Linux 2 AMI.
- Ensure that your security group is configured to allow SSH access
(port 22).

Step 1.2: Connect to the EC2 Instance


- Use SSH to connect to your EC2 instance:
ssh -i /path/to/your-key.pem ec2-user@your-ec2-public-dns
2. Install Required Tools

Step 2.1: Update System Packages


- Start by updating the YUM package manager to ensure all
packages are up to date:
sudo yum update -y
Step 2.2: Install Git
- Git is needed to clone the repository:
sudo yum install git -y
Step 2.3: Install Java
- Install OpenJDK 11, which is required for compiling and running
Java applications:
sudo amazon-linux-extras install java-openjdk11 -y
Step 2.4: Install Maven
- Maven is used for compiling, running unit tests, and packaging the
application:
sudo yum install maven -y
3. Clone the GitHub Repository

Step 3.1: Clone the Repository


- Use Git to clone the repository to your local directory:
git clone https://github.com/preethid/addressbook.git
Step 3.2: Navigate to the Project Directory
- Change the directory to the cloned repository:
cd addressbook
4. Compile the Project

Step 4.1: Compile the Code


- Use Maven to compile the Java code:
mvn compile
This command compiles the source code of the project.

5. Run Unit Tests

Step 5.1: Execute Unit Tests


- Run the unit tests included in the project:
mvn test
This command executes the test cases in the project, ensuring the
code works as expected.

6. Package the Application

Step 6.1: Package the Code


- Package the compiled code into a JAR file:
mvn package
This command creates a JAR file in the `target` directory of the
project, which can be deployed as a complete application.

7. Verify the Process

Step 7.1: List the Contents of the Target Directory


- Check that the JAR file has been successfully created:
ls target/
You should see a JAR file named something like `addressbook-1.0-
SNAPSHOT.jar`.

8. Clean Up (Optional)

Step 8.1: Clean the Maven Build


- To clean up the project and remove the `target` directory:
mvn clean

#### Conclusion
You have successfully cloned a project from a GitHub repository to
your local EC2 instance, compiled the code, ran unit tests, and
packaged the application using Maven. This process is essential for
ensuring that the project is correctly set up and that the code is
working as intended before deployment.

### Simple Project: Configuring a Freestyle Job to Compile Java


Code from GitHub with Automatic Maven Installer and Manually Set
Java Path on Jenkins GUI

#### Scenario
You need to create a Jenkins Freestyle job that pulls a Java project
from a GitHub repository
(`https://github.com/preethid/addressbook.git`), compiles the code
using Maven, and uses a manually set Java path for an already
installed Java version. Maven will be configured as an automatic
installer in Jenkins.

1. Prerequisites

Step 1.1: Install Jenkins (if not already installed)


- Ensure Jenkins is installed on your server and accessible via a web
browser.
- Start Jenkins if it's not running:
sudo systemctl start jenkins
- Access Jenkins through your browser by navigating to
`http://<your-server-ip>:8080`.

Step 1.2: Install Java on Your Server


- Ensure that Java is installed on the server where Jenkins is
running. Verify the installation:
java -version
- If Java is not installed, install it according to your operating
system's instructions.

2. Configure Jenkins for Java and Maven

Step 2.1: Log into Jenkins


- Open your web browser and log into Jenkins using your
credentials.

Step 2.2: Navigate to Global Tool Configuration


- From the Jenkins dashboard, go to `Manage Jenkins` > ` Tools`.

Step 2.3: Configure JDK Installation


- Scroll down to the `JDK` section.
- Add JDK:
- Click `Add JDK`.
- Name: Name the JDK, e.g., `JDK 11`.
- Uncheck the `Install automatically` box (since Java is already
installed on your server).
- JAVA_HOME: Enter the path to the Java installation on your server.
You can find this path with the following command:
readlink -f $(which java) | sed "s:/bin/java::"
- Example path: `/usr/lib/jvm/java-11-openjdk-11.0.11.9-
0.el7_9.x86_64`.

Step 2.4: Configure Maven Installation


- Scroll down to the `Maven` section.
- Add Maven:
- Click `Add Maven`.
- Name: Name the Maven installation, e.g., `Maven 3.8.7`.
- Install automatically: Leave this option checked.
- Version: Select the Maven version you want Jenkins to
automatically install.

Step 2.5: Save the Configuration


- Click `Save` to apply the changes.

3. Create and Configure the Jenkins Freestyle Job

Step 3.1: Create a New Job


- From the Jenkins dashboard, click `New Item`.
- Enter a name for your project (e.g., `AddressBook-Build`) and
select `Freestyle project`. Click `OK`.

Step 3.2: Configure the Source Code Management


- In the job configuration screen, under the `Source Code
Management` section, select `Git`.
- Repository URL: Enter the GitHub repository URL:
`https://github.com/preethid/addressbook.git`.
Step 3.3: Configure the Build Environment
- Scroll down to the `Build Environment` section.
- Ensure that `Provide Node & Maven tool installers` is checked.

Step 3.4: Configure the Build


- Scroll down to the `Build` section.
- Add Build Step: Click `Add build step` > `Invoke top-level Maven
targets`.
- Maven Version: Select the Maven installation you configured
earlier (`Maven 3.8.7`).
- Goals: Enter `clean compile` to clean the workspace and compile
the code.

Step 3.5: Save the Job Configuration


- Click `Save` to create the job.

4. Build and Validate the Job

Step 4.1: Run the Job


- From the job’s dashboard, click `Build Now`.
- Monitor the build progress by clicking on the build number under
the `Build History` section and then selecting `Console Output`.

Step 4.2: Validate the Output


- Ensure the build completes successfully, with the code compiled
without errors.

Step 4.3: Check Maven and Java Versions


- In the console output, verify that Jenkins used the correct versions
of Maven and Java as specified during the configuration.
#### Conclusion
You have successfully configured a Jenkins Freestyle job to clone a
Java project from GitHub, compile the code using Maven, and utilize
a manually set Java path for an already installed Java version. This
setup allows you to automate the build process for Java projects,
ensuring consistency across builds.

DevOps Training
WhatsApp *91 8886740600*

Preethi Dovala

akshay alone

Home


Syllabus


Live Training


Video Tutorials

 Policies

Blog


< Jenkins Home

Jenkins-Day-4
QUIZ
### Project: Running Maven Tests and Validation on Jenkins GUI

#### Scenario Overview


This project will guide you through setting up a Jenkins Freestyle
job to run Maven tests for a Java project cloned from a GitHub
repository. The tasks include configuring the job, running the Maven
tests, and validating the results—all through the Jenkins GUI.

1. Create a New Jenkins Freestyle Project


- Task: Set up a new Jenkins job.
- Action:
- Navigate to the Jenkins dashboard.
- Click on `New Item`.
- Enter a project name (e.g., `AddressBook-Test`).
- Select `Freestyle project` and click `OK`.
- Explanation: This creates a new Jenkins Freestyle project where
you'll configure the Maven build.

2. Configure Source Code Management


- Task: Link the project to the GitHub repository.
- Action:
- In the job configuration, scroll down to the `Source Code
Management` section.
- Select `Git`.
- Enter the Repository URL:
`https://github.com/preethid/addressbook.git`.
- Explanation: This step pulls the Java project from the GitHub
repository.

3. Add Maven as a Build Tool


- Task: Set up Maven for the project.
- Action:
- Scroll down to the `Build` section.
- Click `Add build step` and select `Invoke top-level Maven targets`.
- In the `Goals` field, enter `test`.
- Select the appropriate Maven version from the drop-down list.
- Explanation: This step configures Jenkins to run Maven tests as
part of the build process.

4. Configure Java Path Manually


- Task: Ensure the correct Java version is used.
- Action:
- Go to `Manage Jenkins` > `Tools`.
- Under the `JDK` section, ensure the correct Java version is set, or
add a new JDK if necessary.
- In the job configuration, under the `Build Environment` section,
select the JDK version.
- Explanation: This ensures that the job uses the correct Java
version installed on your system.

5. Save and Run the Job


- Task: Execute the configured job.
- Action:
- Click `Save` to save the job configuration.
- From the project dashboard, click `Build Now` to run the job.
- Explanation: This triggers the job to clone the repository, run the
Maven tests, and compile the code.

6. Validate Test Results


- Task: Review the output of the Maven tests.
- Action:
- After the build is complete, click on the build number in the `Build
History` section.
- Select `Console Output` to view the results.
- Optionally, navigate to `Workspace` > `target` > `surefire-reports`
to view detailed test reports.
- Explanation: This allows you to verify that the tests ran
successfully and to inspect any failures or issues.

#### Summary
In this project, you created a Jenkins Freestyle job, configured it to
run Maven tests for a Java project from GitHub, and validated the
results—all using the Jenkins GUI. Each step included brief
explanations to ensure a smooth setup and execution.
### Project: Installing Jenkins JUnit Plugin and Publishing Test
Reports

#### Scenario Overview


This project will guide you through installing the JUnit plugin in
Jenkins, setting up a job to run tests, and configuring post-build
actions to publish the test reports.

1. Install the JUnit Plugin


- Task: Install the JUnit plugin in Jenkins.
- Action:
- Go to `Manage Jenkins` > `Manage Plugins`.
- In the `Available` tab, search for `JUnit`.
- Select the `JUnit` plugin and click `Install without restart`.
- Explanation: This step installs the JUnit plugin, enabling Jenkins to
process and display JUnit test results.

2. Create a New Jenkins Freestyle Project


- Task: Set up a new Jenkins job for running tests.
- Action:
- From the Jenkins dashboard, click `New Item`.
- Enter a project name (e.g., `JUnit-Test-Project`).
- Select `Freestyle project` and click `OK`.
- Explanation: This creates a new Jenkins job where you can
configure test execution and report publishing.

3. Configure Source Code Management


- Task: Link the project to a GitHub repository with JUnit tests.
- Action:
- In the job configuration, scroll down to the `Source Code
Management` section.
- Select `Git` and enter the repository URL (e.g.,
`https://github.com/preethid/addressbook.git`).
- Explanation: This pulls the project code from GitHub, including
JUnit test cases.

4. Add a Build Step to Run Maven Tests


- Task: Run the Maven test phase to execute JUnit tests.
- Action:
- Scroll down to the `Build` section.
- Click `Add build step` and select `Invoke top-level Maven targets`.
- In the `Goals` field, enter `test`.
- Explanation: This step configures Jenkins to run the JUnit tests
during the build process.

5. Configure Post-Build Action to Publish JUnit Test Results


- Task: Set up Jenkins to publish JUnit test reports after the build.
- Action:
- Scroll down to the `Post-build Actions` section.
- Click `Add post-build action` and select `Publish JUnit test result
report`.
- In the `Test report XMLs` field, enter
`target/surefire-reports/*.xml`.
- Explanation: This action tells Jenkins to collect and publish the
JUnit test results after the build completes.

6. Save and Run the Job


- Task: Execute the job to run tests and publish reports.
- Action:
- Click `Save` to save the job configuration.
- Click `Build Now` to start the job.
- Explanation: This triggers the job to clone the repository, run the
tests, and publish the test results.

7. Validate the Published Test Reports


- Task: Review the test report published by Jenkins.
- Action:
- After the build is complete, click on the build number in the `Build
History` section.
- Navigate to `Test Result` to view the test report summary.
- Explanation: This allows you to verify the test results and ensure
they are correctly published.

### Summary
In this project, you installed the JUnit plugin in Jenkins, set up a
Freestyle job to run tests, and configured post-build actions to
publish the test reports. Each step included one-line explanations to
guide you through the process.

### Project: Configuring Maven Package Goal in Jenkins GUI with


Validation
#### Scenario Overview
This project will guide you through configuring a Jenkins Freestyle
job to run the `mvn package` goal for a Java project. You'll configure
the job, run the Maven package goal, and validate the output—all
through the Jenkins GUI.

1. Create a New Jenkins Freestyle Project


- Task: Set up a new Jenkins job.
- Action:
- Navigate to the Jenkins dashboard.
- Click on `New Item`.
- Enter a project name (e.g., `Maven-Package-Project`).
- Select `Freestyle project` and click `OK`.
- Explanation: This creates a new Jenkins job where you can
configure the Maven build.

2. Configure Source Code Management


- Task: Link the project to a GitHub repository.
- Action:
- In the job configuration, scroll down to the `Source Code
Management` section.
- Select `Git`.
- Enter the Repository URL:
`https://github.com/preethid/addressbook.git`.
- Explanation: This step pulls the Java project from the GitHub
repository.

3. Add a Build Step to Run Maven Package


- Task: Set up the Maven package goal.
- Action:
- Scroll down to the `Build` section.
- Click `Add build step` and select `Invoke top-level Maven targets`.
- In the `Goals` field, enter `package`.
- Select the appropriate Maven version from the drop-down list.
- Explanation: This step configures Jenkins to run the Maven
`package` goal, which compiles, tests, and packages the code.

4. Save and Run the Job


- Task: Execute the job to run the Maven package goal.
- Action:
- Click `Save` to save the job configuration.
- From the project dashboard, click `Build Now` to run the job.
- Explanation: This triggers the job to clone the repository, run the
Maven package goal, and compile the code.

5. Validate the Package Output


- Task: Verify that the JAR file was created successfully.
- Action:
- After the build is complete, click on the build number in the `Build
History` section.
- Select `Workspace` > `target` to check for the generated JAR file
(e.g., `addressbook-1.0-SNAPSHOT.jar`).
- Explanation: This allows you to verify that the Maven package goal
was executed successfully and the JAR file was created.

6. Inspect the Build Logs


- Task: Review the console output to ensure the packaging process
completed without errors.
- Action:
- Click on the build number in the `Build History` section.
- Select `Console Output` to view the detailed build logs.
- Explanation: This helps confirm that the Maven `package` goal ran
as expected and the build was successful.

### Summary
In this project, you configured a Jenkins Freestyle job to run the
Maven `package` goal for a Java project from GitHub, executed the
job, and validated the output—all through the Jenkins GUI. Each step
included one-line explanations to guide you through the process.

### Project: Configuring Jenkins with Build Pipeline Plugin, Build


Triggers, and Post-Build Actions for Compile, Unit Test, and Package

#### Scenario Overview


This project will guide you through installing the Build Pipeline
plugin in Jenkins, configuring a Jenkins job to compile, test, and
package a Java project using Maven, and setting up build triggers
and post-build actions. You will validate each step throughout the
process.

1. Install the Build Pipeline Plugin


- Task: Install the Build Pipeline plugin from the Jenkins Plugin
Manager.
- Action:
- Navigate to `Manage Jenkins` > `Manage Plugins`.
- Search for `Build Pipeline` in the `Available` tab.
- Select the plugin and click `Install without restart`.
- Explanation: This step installs the Build Pipeline plugin, which
allows you to create and manage build pipelines.

2. Create a New Jenkins Freestyle Project


- Task: Set up a new Jenkins job.
- Action:
- Navigate to the Jenkins dashboard.
- Click on `New Item`.
- Enter a project name (e.g., `Pipeline-Maven-Project`).
- Select `Freestyle project` and click `OK`.
- Explanation: This creates a new Jenkins job to configure Maven
build steps and triggers.

3. Configure Source Code Management


- Task: Link the project to a GitHub repository.
- Action:
- In the job configuration, scroll down to the `Source Code
Management` section.
- Select `Git`.
- Enter the Repository URL:
`https://github.com/preethid/addressbook.git`.
- Explanation: This step pulls the Java project from the GitHub
repository.

4. Add a Build Trigger


- Task: Set up a trigger to automatically build the job on SCM
changes.
- Action:
- Scroll down to the `Build Triggers` section.
- Select `Poll SCM` and enter the schedule (e.g., `H/5 * * * *` for
every 5 minutes).
- Explanation: This configures Jenkins to automatically trigger a
build whenever there are changes in the source code repository.

5. Add a Build Step to Compile the Code


- Task: Run the Maven `compile` goal.
- Action:
- Scroll down to the `Build` section.
- Click `Add build step` and select `Invoke top-level Maven targets`.
- In the `Goals` field, enter `compile`.
- Explanation: This step configures Jenkins to compile the code as
part of the build process.

6. Add a Build Step to Run Unit Tests


- Task: Run the Maven `test` goal.
- Action:
- Click `Add build step` again and select `Invoke top-level Maven
targets`.
- In the `Goals` field, enter `test`.
- Explanation: This step configures Jenkins to run unit tests during
the build process.

7. Add a Build Step to Package the Application


- Task: Run the Maven `package` goal.
- Action:
- Click `Add build step` again and select `Invoke top-level Maven
targets`.
- In the `Goals` field, enter `package`.
- Explanation: This step configures Jenkins to package the
application into a JAR file.

8. Add a Post-Build Action to Publish Test Results


- Task: Publish the results of the unit tests.
- Action:
- Scroll down to the `Post-build Actions` section.
- Click `Add post-build action` and select `Publish JUnit test result
report`.
- In the `Test report XMLs` field, enter
`target/surefire-reports/*.xml`.
- Explanation: This action publishes the JUnit test results after the
build is completed.

9. Save and Run the Job


- Task: Execute the job to perform the Maven build steps.
- Action:
- Click `Save` to save the job configuration.
- Click `Build Now` to manually trigger the first build.
- Explanation: This triggers the job to compile, test, and package
the code, and publish the test results.

10. Validate the Build Outputs


- Task: Verify that the build steps completed successfully.
- Action:
- After the build is complete, click on the build number in the `Build
History` section.
- Review the `Console Output` for successful completion of
`compile`, `test`, and `package` goals.
- Explanation: This allows you to confirm that each Maven goal was
executed as expected.

11. Create a New Build Pipeline View


- Task: Visualize the build process using the Build Pipeline plugin.
- Action:
- From the Jenkins dashboard, click on the `+` sign to add a new
view.
- Select `Build Pipeline View` and enter a name (e.g., `Maven
Pipeline`).
- Configure the view to include the `Pipeline-Maven-Project` as the
initial job.
- Explanation: This step creates a pipeline view that visualizes the
sequence of jobs and their results.

12. Inspect the Pipeline and Validate


- Task: Review the pipeline view to ensure that all stages are
represented and that the job has executed successfully.
- Action:
- Click on the `Maven Pipeline` view.
- Inspect the different stages (Compile, Unit Test, Package) for
successful execution.
- Explanation: This allows you to visualize and validate the entire
build process in a pipeline format.

### Summary
In this project, you installed the Build Pipeline plugin, configured a
Jenkins Freestyle job to compile, test, and package a Java project
using Maven, set up build triggers, and post-build actions, and
validated the build process through the Jenkins GUI. The final step
involved creating and inspecting a pipeline view to visualize the
entire build process.
### Project: Password-less SSH Configuration Between Master and
Slave

#### Objective:
To set up password-less SSH authentication between a master and
slave server for the `user1` account, allowing secure and convenient
access without a password prompt.

1. Switch to Root User on Both Servers


- Explanation: Ensure you have administrative privileges on both
servers to perform the required tasks.
- Command:
sudo su -
2. Create `user1` on Both Master and Slave Servers
- Explanation: Create a new user account (`user1`) on both the
master and slave servers.
- Command:
useradd user1

3. Set Password for `user1` on Both Servers


- Explanation: Assign a password to `user1` on both servers for
initial SSH login.
- Command:
passwd user1

4. Enable `PasswordAuthentication` on Slave Server


- Explanation: Allow password-based SSH authentication on the
slave server by enabling `PasswordAuthentication`.
- Commands:
vi /etc/ssh/sshd_config
- Edit the file:
- Find the line `PasswordAuthentication no` and change it to
`PasswordAuthentication yes`.
- Restart the SSH Daemon:
systemctl restart sshd
5. Generate SSH Key Pair for `user1` on Master Server
- Explanation: Create a public/private SSH key pair for `user1` on
the master server.
- Command:
su - user1
ssh-keygen -t rsa -b 2048
- Details:
- Accept the default file location by pressing `Enter`.
- Optionally set a passphrase or press `Enter` for no passphrase.

6. Copy the SSH Public Key to the Slave Server


- Explanation: Transfer `user1`'s public key from the master to the
slave server to allow password-less login.
- Command:
ssh-copy-id -i ~/.ssh/id_rsa.pub user1@slave_ip
- Details:
- Replace `slave_ip` with the actual IP address of the slave server.
- When prompted, enter `user1`'s password on the slave to
complete the key transfer.

7. Test SSH Connection from Master to Slave for `user1`


- Explanation: Verify that `user1` can SSH into the slave server
without being prompted for a password.
- Command:
ssh user1@slave_ip
- Details:
- Replace `slave_ip` with the actual IP address of the slave server.
- If successful, `user1` should log in to the slave server without a
password prompt.

#### Validation Steps

1. Check User Existence on Both Servers


- Command:
grep user1 /etc/passwd
2. Verify SSH Configuration on Slave
- Command:
grep PasswordAuthentication /etc/ssh/sshd_config
3. Confirm SSH Key Pair on Master
- Command:
ls -l /home/user1/.ssh/
4. Check for the Copied Public Key on Slave
- Command:
cat /home/user1/.ssh/authorized_keys
5. Test Password-less SSH Login
- Command:
ssh user1@slave_ip
This project outlines the step-by-step process of setting up
password-less SSH authentication between a master and slave
server. Each command is explained briefly, providing a clear and
practical guide for implementation.

### Project: Prepare and Add Node as Jenkins Slave with


Configuration

#### Objective
Prepare a Jenkins slave node by installing the necessary tools (Git,
Java, Maven), set the environment, and add the node to Jenkins
master with specified settings for executors, remote root directory,
labels, SSH launch method, and availability.

#### 1. Prepare the Node as Jenkins Slave

##### 1.1 Install Git


- Task: Install Git for version control.
- Command:
sudo yum install git -y
- Explanation: Git is installed to enable code version management.

##### 1.2 Install Java


- Task: Install Java Development Kit (JDK).
- Command:
sudo amazon-linux-extras install java-openjdk11 -y
- Explanation: Java is required for Jenkins and Maven builds.

##### 1.3 Set JAVA_HOME Directory


- Task: Set the JAVA_HOME environment variable.
- Command:
echo "export JAVA_HOME=$(dirname $(dirname $(readlink $
(readlink $(which javac)))))" | sudo tee -a /etc/profile
source /etc/profile
- Explanation: This sets and exports the Java home directory
globally.

##### 1.4 Install Maven


- Task: Install Apache Maven for building projects.
- Command:
sudo yum install maven -y
- Explanation: Maven is needed for building and managing Java
projects.

#### 2. Add a New Node to Jenkins Master

1. Login to Jenkins GUI


- Navigate to Manage Jenkins > Nodes > New Node.

2. Provide the following settings:

- Node Name: Enter a unique name for the new node.

- Type: Permanent Agent.

- Remote Root Directory: `/tmp` or any other Folder


- Explanation: Defines the root directory for Jenkins on the slave
node.

- No. of Executors: `2` or as per your system Capacity


- Explanation: Number of parallel jobs the node can handle.

- Labels: `slave-node`
- Explanation: Labels allow Jenkins to assign specific jobs to this
node.
- Usage: `Only build jobs with label expressions matching this node`
- Explanation: Restrict jobs to build only if they match the label.

- Launch Method: Launch agent via SSH.

- Host: Enter the IP address or DNS of the slave node.

- Credentials: Select pre-configured SSH credentials for the slave.

- Host Key Verification Strategy: Manually Trusted Key Verification


Strategy.

- Availability: Keep this agent online as much as possible.


- Explanation: Configures the node to remain online and available
for jobs.

3. Save and Launch


- Once all settings are provided, save the configuration and click on
"Launch agent" to initiate the connection.

#### 3. Validation

- Task: Validate the connection by checking the node's status in


Jenkins.
- Steps:
- After launching the agent, go to Manage Jenkins > Manage Nodes
and Clouds.
- The newly added node should show online status.

This setup ensures the node is ready to run builds from Jenkins,
with Java, Maven, and Git installed for necessary build tasks.
### Project: Add a Job on Jenkins Slave Node (Label: `slave-node`)
to Run Maven Compile Job Without Poll SCM

1. Add a New Maven Compile Job on Jenkins

1. Login to Jenkins GUI


- Task: Access Jenkins dashboard.
- Explanation: Navigate to Jenkins’ web interface.

2. Create a New Job


- Task: Create a new Maven compile job.
- Steps:
- From the Dashboard, click New Item.
- Enter the Job Name: `Maven-Compile-Job-Slave`.
- Choose Freestyle Project.
- Click OK.
- Explanation: This creates a new job to compile a Maven project.

3. Configure the Job to Run on the Slave Node


- Task: Set the job to run on the node labeled `slave-node`.
- Steps:
- Under General section, check Restrict where this project can be
run.
- In the Label Expression field, enter `slave-node`.
- Explanation: Ensures the job runs only on the slave node with the
label `slave-node`.

2. Configure Source Code Management

1. Source Code Management Setup


- Task: Pull the source code from a Git repository.
- Steps:
- Under Source Code Management, select Git.
- In the Repository URL field, enter the Git URL:
`https://github.com/preethid/addressbook.git`.
- Explanation: Configures the job to clone the project from the
repository.
3. Configure Build Step for Maven Compilation

1. Set Up Maven Goals


- Task: Add the Maven compilation steps.
- Steps:
- Under the Build section, click Add build step > Invoke top-level
Maven targets.
- Set Goals: `clean compile`.
- Explanation: This will run Maven `clean` and `compile` tasks,
ensuring the project is compiled on the slave node.

4. Save the Job

1. Save the Job Configuration


- Task: Save the configured job.
- Steps:
- Scroll down and click Save.
- Explanation: This saves the job setup and makes it ready for
execution.

5. Manually Trigger and Validate the Maven Compile Job

1. Manually Trigger the Job


- Task: Trigger the job manually.
- Steps:
- On the job's page, click Build Now.
- Explanation: This manually triggers the Maven compile job on the
slave node.

2. Monitor the Build Execution


- Task: Monitor the build process on the slave node.
- Steps:
- Go to the Build History section and click on the running build.
- Check the Console Output for the Maven build steps and ensure
there are no errors.
- Explanation: Verifies that the job is running as expected and
compiling the Maven project successfully.
6. Validate Execution on Slave Node

1. Ensure Job Runs on the Slave Node


- Task: Check the node on which the job ran.
- Steps:
- Go to Manage Jenkins > Nodes > slave-node.
- Verify that the job ran on the `slave-node` by checking the Console
Output.
- Explanation: This ensures the Maven compile job is being executed
on the correct slave node.

By following this sequence, you can configure and manually run a


Maven compile job on a slave node without using Poll SCM. The job
will be manually triggered and compiled on the node labeled `slave-
node`.

DevOps Training
WhatsApp *91 8886740600*

Preethi Dovala

akshay alone

Home


Syllabus


Live Training


Video Tutorials

 Policies

Blog


< Jenkins Home

Jenkins-Day-5
QUIZ
### Project: Configuring Pipeline as Code in Jenkins GUI

This project outlines the steps to create a pipeline in Jenkins using


"Pipeline as Code" with three stages: Compile, Test, and Package.
The pipeline script will output a message at each stage.

### 1. Search for Pipeline Plugin


Explanation: Ensure that Jenkins is ready to support pipelines by
installing the required plugin.
- Go to Jenkins Dashboard -> Manage Jenkins -> Manage Plugins.
- Under the Available tab, search for Pipeline.
- Check the box next to Pipeline and click Install without restart.

### 2. Install Plugin: Pipeline Multibranch


Explanation: Enable support for multibranch pipelines & Pipeline
stage view if necessary.
- In Manage Jenkins -> Manage Plugins, search for Pipeline
Multibranch & Pipeline stage view.
- Install Pipeline: Multibranch & stage view. plugin by checking the
box and clicking Install without restart.
### 3. Create a Job with Pipeline Type
Explanation: Set up a new Jenkins job that supports pipeline
configuration.
- Go to the Jenkins Dashboard.
- Click on New Item.
- Enter the job name (e.g., `pipeline-project`).
- Select Pipeline as the project type.
- Click OK to create the job.

### 4. Create a Pipeline Script


Explanation: Define a pipeline script with three stages: Compile,
Test, and Package.
- In the job configuration page, scroll down to the Pipeline section.
- Choose Pipeline Script.
- Enter the following script in the pipeline script box:

pipeline {
agent any

stages {
stage('Compile') {
steps {
echo 'Compiling the source code...'
}
}
stage('Test') {
steps {
echo 'Running the tests...'
}
}
stage('Package') {
steps {
echo 'Packaging the application...'
}
}
}
}

- Click Save.
### 5. Run the Pipeline Job
Explanation: Trigger the pipeline execution manually.
- Go to the Project Dashboard of the newly created pipeline.
- Click Build Now to start the pipeline.
- You should see the stages run in sequence: Compile, Test, and
Package, with each stage echoing its name.

### 6. Validate the Pipeline Execution


Explanation: Confirm that each stage in the pipeline has executed
successfully.
- After the build completes, click on the build number in the Build
History.
- Check the Console Output to see the echo messages for each
stage:
- Compiling the source code...
- Running the tests...
- Packaging the application...

### Summary:
- Installed necessary pipeline plugins.
- Created a Jenkins pipeline job.
- Configured a basic pipeline script with three stages.
- Validated the output of each stage via console logs.

Groovy Code
pipeline {
agent any - This defines the start of a Jenkins pipeline block. The entire structure of the pipeli

stages {
stage('Compile') {
steps { - Specifies that the pipeline can be executed on any available Jenkins agent (no
echo 'Compiling the node in the cluster to run the pipeline unless yo
source code...'
}
}
stage('Test') { - The stages block is used to define multiple stages in the pipeline. Each stage r
steps { su
echo 'Running the tests...'
}
- Defines a stage in the pipeline named Compile. This is the first stage of the p
- The name inside `stage('...')` is the name that will appear in the Je

- Inside each stage, the steps block defines the actual commands or tasks to execut
this could involve running shell com

6
- `echo` is a Jenkins Pipeline step that outputs text to the console. This line will pr

- It serves as a simple

- This defines the second stage named Test. This stage will be responsible

- The steps block for the Test stage, just like in the Compile stage, defines the

- This command will print "Running the tests..." to the console wh


- Again, in a real scenario, this could be replaced by actual

- This defines the third stage called Package, where the source code is packag

- The steps block for the Package stage, where


}
stage('Package') {
steps { 1
echo 'Packaging the - This will print "Packaging the application..." to the console w
application...' - In a real-world case, this would be replaced b
}
}
}
} - Closes the respective blocks for steps, stage, and pipeline. Every bl

### Project: Jenkins Pipeline with "Pipeline Script from SCM"


This project demonstrates how to set up a Jenkins pipeline by
fetching a Jenkinsfile from a GitHub repository. This setup allows
Jenkins to automatically pull the pipeline script and run it directly
from the source control.

### Scenario:
You need to create a Jenkins pipeline using the "Pipeline Script from
SCM" option, where the Jenkinsfile is stored in a GitHub repository.

#### 1. Create a New Jenkins Pipeline Job

- Explanation: Open Jenkins and create a new pipeline job that will
run based on the Jenkinsfile from a GitHub repository.
- Action:
- Navigate to Jenkins dashboard.
- Click on `New Item`.
- Enter a name for your project (e.g., "GitHub-Pipeline-Job").
- Select `Pipeline` and click `OK`.

#### 2. Configure the Pipeline to Use "Pipeline Script from SCM"

- Explanation: Specify that the pipeline script (Jenkinsfile) will be


retrieved from SCM, in this case, GitHub.
- Action:
- Scroll down to the `Pipeline` section.
- In the `Definition` dropdown, select `Pipeline script from SCM`.
- In the `SCM` dropdown, choose `Git`.

#### 3. Set Up GitHub Repository Details

- Explanation: Provide the GitHub repository URL where the


Jenkinsfile is located.
- Action:
- In the `Repository URL`, enter the URL of the GitHub repository
(e.g., `https://github.com/username/repository.git`). or
https://github.com/preethid/addressbook.git
- If your repository is private, add credentials by clicking the `Add`
button and configuring the credentials for GitHub access.
#### 4. Configure the Branch and Jenkinsfile Path

- Explanation: Specify the branch and the location of the Jenkinsfile


in the repository.
- Action:
- In the `Branch Specifier` field, specify the branch name (e.g.,
`*/main` or `*/master`).
- Under `Script Path`, provide the location of the Jenkinsfile in the
repository (e.g., `Jenkinsfile` if it's located in the root of the repo, or
`folder-name/Jenkinsfile` if it's nested).

#### 5. Configure Build Triggers (Optional)

- Explanation: Optionally, configure how often the pipeline should


trigger (e.g., on changes to SCM or scheduled builds).
- Action:
- Scroll to `Build Triggers`.
- Select `Poll SCM` if you want the job to run automatically when
changes are pushed to GitHub.
- Define the polling schedule in cron syntax (e.g., `H/5 * * * *` to poll
every 5 minutes).

#### 6. Save the Job

- Explanation: Save the job configuration.


- Action:
- Click `Save` at the bottom of the page.

#### 7. Run the Pipeline Job

- Explanation: Manually trigger the job to validate if it fetches the


Jenkinsfile from the GitHub repository and runs successfully.
- Action:
- Click `Build Now` to trigger the job manually.
- Monitor the build by clicking on the `Console Output` of the
running build.
#### 8. Validate the Pipeline Execution

- Explanation: Validate that the pipeline executed the stages


defined in the Jenkinsfile fetched from the GitHub repository.
- Action:
- Check the console logs to ensure that each stage (Compile, Test,
Package, etc.) runs as defined in the Jenkinsfile.
- Ensure no errors occurred during the build process.

By following these steps, you will have a fully functioning Jenkins pipeline,
pulling and executing a Jenkinsfile from a GitHub repository.

### Project: Jenkins Pipeline with Git Branch and Parameters

This project guides you through creating a Git branch, cloning a


repository, adding a Jenkinsfile with stages and parameters,
pushing the changes to GitHub, and setting up a Jenkins pipeline to
run using the Jenkinsfile from SCM.

### Scenario:
You need to create a Git branch, clone a repository, add a Jenkinsfile
with `dev`, `test`, and `prod` stages, define parameters, push the
changes to GitHub, and configure Jenkins to execute the pipeline
using the "Pipeline script from SCM" feature.

#### 1. Create a New Git Branch (`feature/devops_1`)

- Explanation: Create a new branch for the development work.


- Command:

git clone https://github.com/preethid/addressbook.git


cd addressbook
git checkout -b feature/devops_1
#### 2. Create the Jenkinsfile with 3 Stages and Parameters

- Explanation: Create a `Jenkinsfile` with stages for development,


testing, and production, and include a parameters block to define
input parameters.
- Action:
- Open your text editor Example VIM, and create a new `Jenkinsfile`
with the following content:
vim jenkinsfile

string(name: 'ENVIRONMENT', defaultValue: 'dev', de


booleanParam(name: 'RUN_TESTS', default
choice(name: 'DEPLOY_SERVER', choices: ['dev', 'test', 'prod'], des

if
echo "Bu

echo "Running tests in the ${para

if (par
e

echo "Deploying to ${

- Explanation:
- Parameters:
- `ENVIRONMENT`: Defines the environment (default: dev).
- `RUN_TESTS`: Boolean parameter to decide whether to run tests.
- `DEPLOY_SERVER`: A choice parameter to specify which server to
deploy to (dev, test, or prod).
- Stages:
- Dev Stage: Simulates development environment build.
- Test Stage: Runs tests based on the parameter.
- Prod Stage: Deploys to the selected server.

#### 3. Push the Changes to GitHub (`feature/devops_1`)

- Explanation: Push the Jenkinsfile and the changes to your Git


branch.
- Commands:

git add Jenkinsfile


git commit -m "Added Jenkinsfile with stages and parameters"
git push origin feature/devops_1

#### 4. Create a New Jenkins Pipeline with "Pipeline Script from


SCM"

- Explanation: In Jenkins, create a new pipeline job that pulls the


Jenkinsfile from the `feature/devops_1` branch in the GitHub
repository.
- Steps:
- In Jenkins, navigate to the dashboard and click `New Item`.
- Name your pipeline (e.g., "Addressbook-Pipeline"), select
`Pipeline`, and click `OK`.
- Scroll down to the `Pipeline` section, and under `Definition`, select
`Pipeline script from SCM`.
- Under `SCM`, choose `Git`.
- In the `Repository URL` field, enter
`https://github.com/preethid/addressbook.git`.
- In the `Branch Specifier`, enter `*/feature/devops_1`.
- In the `Script Path`, enter `Jenkinsfile`.
- Click `Save`.

#### 5. Build the Pipeline

- Explanation: Manually trigger the pipeline and provide values for


the defined parameters.
- Steps:
- After saving the pipeline configuration, click `Build with
Parameters` in the Jenkins project.
- Enter values for `ENVIRONMENT`, `RUN_TESTS`, and
`DEPLOY_SERVER` parameters.
- Click `Build`.

#### 6. Validate the Build Stages

- Explanation: Verify that each stage (`dev`, `test`, and `prod`) runs
as expected based on the parameter values you provided.
- Steps:
- Monitor the `Console Output` to check that the stages execute
correctly.
- Verify that the `Dev Stage`, `Test Stage`, and `Prod Stage` print
the expected messages based on the parameter inputs.

### Summary:

- Created a new Git branch: `feature/devops_1`.


- Cloned the repository and added a Jenkinsfile with 3 stages: `dev`,
`test`, and `prod`.
- Defined parameters for environment, running tests, and
deployment servers.
- Pushed the changes to the `feature/devops_1` branch.
- Configured a Jenkins pipeline with "Pipeline script from SCM" to
fetch the Jenkinsfile from GitHub.
- Ran the pipeline with parameters and validated the stages.

By following these steps, you will have a fully configured Jenkins


pipeline with parameters and multiple stages, using the Jenkinsfile
stored in GitHub.

###line-by-line explanation of the code from the `Jenkinsfile`:

pipeline {
agent any

**pipeline**: Defines the Jenkins pipeline.


**agent any**: Runs the pipeline on any available Jenkins agent.

parameters {
string(name: 'ENVIRONMENT', defaultValue: 'dev', description:
'Environment to deploy to')
booleanParam(name: 'RUN_TESTS', defaultValue: true, description:
'Run tests?')
choice(name: 'DEPLOY_SERVER', choices: ['dev', 'test', 'prod'],
description: 'Choose deployment server')
}

**parameters**: Declares input parameters for the pipeline.


**string(...)**: Defines a string parameter called `ENVIRONMENT`
with a default value of 'dev'.
**booleanParam(...)**: Defines a boolean parameter `RUN_TESTS`
with a default value of `true`.
**choice(...)**: Defines a choice parameter `DEPLOY_SERVER` with
options: 'dev', 'test', 'prod'.
stages {
stage('Dev Stage') {
steps {
script {
if (params.ENVIRONMENT == 'dev') {
echo "Building for development environment"
}
}
}
}

**stages**: Defines multiple stages of the pipeline.


**stage('Dev Stage')**: Defines the first stage, "Dev Stage".
**steps**: Contains the commands or actions to execute in this
stage.
**script { ... }**: A block for executing script logic.
**if (params.ENVIRONMENT == 'dev')**: Checks if the
`ENVIRONMENT` parameter is 'dev'.
**echo "Building for development environment"**: Prints a message
indicating the development environment build.

stage('Test Stage') {
steps {
script {
if (params.RUN_TESTS) {
echo "Running tests in the ${params.ENVIRONMENT} environment"
} else {
echo "Skipping tests"
}
}
}
}

**stage('Test Stage')**: Defines the second stage, "Test Stage".


**if (params.RUN_TESTS)**: Checks if the `RUN_TESTS` parameter is
true.
**echo "Running tests..."**: Prints a message indicating that tests
are being run.
**else**: Executes the next block if the `RUN_TESTS` parameter is
false.
**echo "Skipping tests"**: Prints a message if tests are skipped.

stage('Prod Stage') {
steps {
script {
if (params.DEPLOY_SERVER == 'prod') {
echo "Deploying to production server"
} else {
echo "Deploying to ${params.DEPLOY_SERVER} server"
}
}
}
}
}
}
**stage('Prod Stage')**: Defines the third stage, "Prod Stage".
**if (params.DEPLOY_SERVER == 'prod')**: Checks if the
`DEPLOY_SERVER` parameter is set to 'prod'.
**echo "Deploying to production server"**: Prints a message if
deploying to production.
**else**: Executes the next block if `DEPLOY_SERVER` is not 'prod'.
**echo "Deploying to ${params.DEPLOY_SERVER} server"**: Prints a
message indicating the chosen deployment server.

project outline for creating a Jenkins pipeline that uses "Pipeline


script from SCM" with WHEN conditions based on selected
environments:

### Project: Environment-Based Jenkins Pipeline

#### Scenario
We have three environments: Production, Development, and Test.
Based on the selected environment, a specific message will be
printed.

1. Create a Git Repository:


- Create a new Git repository (e.g., `env-pipeline`) on GitHub or your
preferred Git service.
- Clone the repository to your local machine.
git clone https://github.com/yourusername/env-pipeline.git
cd env-pipeline
2. Create a Jenkinsfile:
- Create a `Jenkinsfile` in the repository with the following content:

choice(name: 'ENVIRONMENT', choices: ['Production', 'Development', 'Test'],

expression { param

echo 'Code D

expression { params.

echo 'Code De
expression {

echo

3. Push the Jenkinsfile to GitHub:


- Add, commit, and push the `Jenkinsfile` to your Git repository.
git add Jenkinsfile
git commit -m "Add Jenkinsfile for environment-based pipeline"
git push origin main

4. Create a New Pipeline Job in Jenkins:


- Open your Jenkins dashboard.
- Click on "New Item".
- Enter a name for the job (e.g., `Environment-Pipeline`).
- Select "Pipeline" and click "OK".

5. Configure the Pipeline Job:


- Scroll down to the "Pipeline" section.
- Set "Definition" to "Pipeline script from SCM".
- Choose "Git" as the SCM.
- Enter the repository URL (e.g.,
`https://github.com/yourusername/env-pipeline.git`).
- Set the branch to `main` (or the appropriate branch).
- Click "Save".

6. Run the Job:


- Click "Build with Parameters" on the left side of the job page.
- Select the environment (Production, Development, or Test) from
the dropdown.
- Click "Build".

7. Validate the Output:


- Once the job completes, click on the build number (e.g., #1) to
view the details.
- Check the console output to see the printed message
corresponding to the selected environment.

### Validation Steps


- Confirm that the Jenkins job runs successfully.
- Ensure the correct message is displayed in the console output
based on the selected environment.

### Summary
This project demonstrates how to create a Jenkins pipeline that
selects actions based on a specified environment using parameters
and conditions. Each selected environment triggers a different
message to be printed in the build logs.

####Create a Jenkins pipeline with "pipeline script from SCM" using


"when" and "input" directives. The pipeline will ask for input to
choose between Production, Development, or Test environments
and display a corresponding message for the selected environment.

### Scenario:
We have three environments: Production, Development, and Test.
The pipeline will prompt for environment selection, and based on
that input, it will print a message for the chosen environment.

#### 1. Create a Git Repository:


- Create a new Git repository (e.g., `ENV-pipeline`) on GitHub or
your preferred Git service.
- Clone the repository to your local machine.

git clone https://github.com/yourusername/ENV-pipeline.git


cd ENV-pipeline
2. Create a Jenkinsfile:
- Create a `Jenkinsfile` in the repository with the following
Add the following content to the `Jenkinsfile`:
message

choice(name: 'ENVIRONMENT', choices: ['Production', 'Development', 'Test'], d

expression { env

echo 'You have

expression { env.S

echo 'You have se

expressio

echo 'You
#### 3. Push the Jenkinsfile to GitHub:
- Add, commit, and push the `Jenkinsfile` to your Git repository.

git add Jenkinsfile


git commit -m "Add Jenkinsfile for ENVironment-based pipeline"
git push origin main

#### 4. Create a New Pipeline Job in Jenkins:


- Open your Jenkins dashboard.
- Click on "New Item".
- Enter a name for the job (e.g., `ENVironment-Pipeline`).
- Select "Pipeline" and click "OK".

Configure the Pipeline Job:


- Scroll down to the "Pipeline" section.
- Set "Definition" to "Pipeline script from SCM".
- Choose "Git" as the SCM.
- Enter the repository URL (e.g.,
`https://github.com/yourusername/ENV-pipeline.git `).
- Set the branch to `main` (or the appropriate branch).
- Click "Save".

#### 5. Run the Pipeline

- Build the Pipeline:


- Go to the project and click "Build Now".
- Jenkins will prompt for environment input. Choose between
"Production", "Development", or "Test" and click "Proceed".

#### 6. Validate the Output

- After running the pipeline, check the console output. It should


display the message based on the environment you selected.
#### Summary:
This project uses the "when" directive and the "input" directive in a
Jenkins pipeline to prompt the user for environment selection.
Depending on the input, the corresponding environment message is
printed. The pipeline script is stored in SCM (GitHub), and Jenkins
pulls the script from the repository to run it.

###Explanation of each line of the provided Jenkins pipeline script:

pipeline {

- pipeline: This starts the definition of the Jenkins pipeline. It


contains the entire workflow configuration.

agent any

- agent any: This directive specifies that the pipeline can run on any
available Jenkins agent.

stages {

- stages: Defines a block that contains multiple stages within the


pipeline. Each stage represents a step in the pipeline process.

stage('Input Environment') {

- stage('Input Environment'): Defines the first stage called 'Input


Environment'. A stage is a step in the pipeline that performs a
specific task.
steps {

- steps: The steps block defines what actions are to be performed in


this stage.

script {

- script: Allows running Groovy code inside a declarative pipeline.


This is used when you need to write more complex logic inside the
pipeline.

env.SELECTED_ENV = input(

- env.SELECTED_ENV = input(...): This assigns the result of an input


prompt to the environment variable `SELECTED_ENV`.

id: 'EnvironmentInput',

- id: A unique identifier for the input step to help Jenkins track it.

message: 'Select the environment to proceed',

- message: The message shown to the user during the input prompt,
asking them to select the environment.
parameters: [
choice(name: 'ENVIRONMENT', choices: ['Production', 'Development',
'Test'], description: 'Choose the environment')
]

- parameters: Defines the parameters for the input step. In this


case, a choice parameter is used.
- choice(...): This creates a dropdown list of choices ('Production',
'Development', 'Test') for the user to select from.

- ): This closes the `input()` function.

}
}
}

- Closing script, steps, and stage: These lines close the respective
blocks.

stage('Production Environment') {

- stage('Production Environment'): Defines the next stage, which


handles the actions specific to the 'Production' environment.
when {
expression { env.SELECTED_ENV == 'Production' }
}

- when: Conditional block that controls the execution of the stage.


This stage will run only if the specified condition is true.
- expression { env.SELECTED_ENV == 'Production' }: This checks if
the selected environment is 'Production'.

steps {
echo 'You have selected the Production environment!'
}

- steps { echo 'You have selected the Production environment!' }:


Prints a message to the Jenkins console stating that 'Production' has
been selected.

- }: Closes the stage for the 'Production' environment.

stage('Development Environment') {
when {
expression { env.SELECTED_ENV == 'Development' }
}
steps {
echo 'You have selected the Development environment!'
}
}

- stage('Development Environment'): Similar to the 'Production


Environment' stage, but it checks if the environment selected is
'Development'.
- when { expression { env.SELECTED_ENV == 'Development' } }:
This stage will run only if 'Development' is selected.
- steps { echo 'You have selected the Development environment!' }:
Prints a message for the Development environment.

stage('Test Environment') {
when {
expression { env.SELECTED_ENV == 'Test' }
}
steps {
echo 'You have selected the Test environment!'
}
}
}
}

- stage('Test Environment'): Similar to the previous stages but for


the 'Test' environment.
- when { expression { env.SELECTED_ENV == 'Test' } }: This stage
runs only if 'Test' is selected.
- steps { echo 'You have selected the Test environment!' }: Prints a
message stating the Test environment is selected.

### Summary:
- The pipeline asks the user to choose an environment (Production,
Development, or Test).
- Based on the user’s selection, the appropriate stage is triggered,
and a message is printed to the console.
- Conditional stages are implemented using the `when` directive
with an `expression` block.

You might also like