Ansible Hands-on



 what is Ansible

It's a simple automation language that can perfectly describe an IT application infrastructure in Ansible Playbooks.

It's an automation engine that runs Ansible Playbooks.

Ansible Tower is an enterprise framework for controlling, securing and managing your Ansible automation with a UI and RESTful API.


Ansible is...

Simple: 

Human readable automation no special coding skills needed tasks executed in order Get productive quicky.


Powerful:

App development configuration management workflow orchestration Orchestrate the app lifecycle


Agentless:

Agentless architecture uses OpenSSH & WinRM No agent to expolit or update More efficient & more secure.



Installing Ansible on Ubuntu 18.04 LTS

$ sudo apt update
$ sudo apt install software-properties-common
$ sudo apt-add-repository --yes --update ppa:ansible/ansible
$ sudo apt install ansible


How Ansible Work:





Modules:

Modules are bits of code transferred to the target system and executed to satisfy the task declaration. Ansible ships with several hundred today!


  • apt/yum
  • copy
  • file
  • get_url
  • git
  • ping
  • debug
  • service
  • template


Module Documentation:

https://docs.ansible.com/ansible/latest/user_guide/modules.html


# List out all modules installed

$ ansible-doc -l

...

copy

cron

...

# Read documentation for installed module

$ ansible-doc copy

> COPY

The [copy] module copies a file on the local box to remote locations. Use the [fetch] module to copy files from remote locations to the local

box. If you need variable interpolation in copied files, use the [template] module.

* note: This module has a corresponding action plugin.

Options (= is mandatory):


Module: Run Commands

If Ansible doesn't have a module that suits your needs there are the "run command" module:


command: Takes the command and executes it on the host. The most secure and predictable.

shell: Executes through a shell like /bin/sh so you can use pipes etc. Be careful.

script: Runs a local script on a remote node after transferring it.

raw: Executes a command without going through the Ansible module subsystem.


Inventory:

Inventory is a collection of hosts (nodes) with associated data and groupings that Ansible can connect and manage.


Hosts

Groups

Inventory-specific data (variables)

Static or dynamic sources


Static Inventory Example:

192.168.0.0

192.168.0.1

192.168.0.2

192.168.0.3

host.example.com


Static Inventory Example

[control]

control ansible_host=192.168.0.0

[web]

node-[1:3] ansible_host=192.168.0.[6:8]

[haproxy]

haproxy ansible_host=192.168.0.2

[all:vars]

ansible_user=ubuntu

ansible_ssh_private_key_file=~/


Ad-Hoc Commands

An ad-hoc command is a single Ansible task to perform quickly, but don’t want to save for later.


# check all my inventory hosts are ready to be

# managed by Ansible

$ ansible all -m ping


# collect and display the discovered facts

# for the localhost

$ ansible localhost -m setup


# run the uptime command on all hosts in the

# web group

$ ansible web -m command -a "uptime"


Sidebar: Discovered Facts

Facts are bits of information derived from examining a host systems that are stored as variables for later use in a play.


$ ansible localhost -m setup

localhost | success >> {

"ansible_facts": {

    "ansible_default_ipv4": {

        "address": "192.168.1.37",

        "alias": "wlan0",

        "gateway": "192.168.1.1",

        "interface": "wlan0",

        "macaddress": "c4:85:08:3b:a9:16",

        "mtu": 1500,

        "netmask": "255.255.255.0",

        "network": "192.168.1.0",

        "type": "ether"

},



Ad-Hoc Commands:


Ansible can work with metadata from various sources and manage their context in the form of variables.


Command line parameters

  • Plays and tasks
  • Files
  • Inventory
  • Discovered facts
  • Roles


Tasks:


Tasks are the application of a module to perform a specific unit of work.


file: A directory should exist

yum: A package should be installed

service: A service should be running

template: Render a configuration file from a template

get_url: Fetch an archive file from a URL

git: Clone a source code repository


Example Tasks in a Play


tasks:

- name: apache2 package is present

apt:

name: apache2

state: latest

- name: latest index.html file is present

copy:

src: files/index.html

dest: /var/www/html/

- name: restart apache2

service:

name: apache2

state: restarted



Handler Tasks:


Handlers are special tasks that run at the end of a play if notified by another

task when a change occurs.


If a configuration file gets changed notify a service restart task that it needs to run.


Example Handler Task in a Play


tasks:

- name: apache2 package is present

apt:

name: apache2

state: latest

notify: restart apache2

- name: latest index.html file is present

copy:

src: files/index.html

dest: /var/www/html/

handlers:

- name: restart apache2

service:

name: apache2

state: restarted



Plays & Playbooks


Plays are ordered sets of tasks to execute against host selections from your inventory. A playbook is a file containing one or more plays.


Playbook Example


---

- name: install and start apache

  hosts: web

 become: yes

vars:

http_port: 80

tasks:

- name: apache2 package is present

apt:

name: apache2

state: latest

- name: latest index.html file is present

copy:

src: files/index.html

dest: /var/www/html/


Human-Meaningful Naming


---

- name: install and start apache

hosts: web

become: yes

vars:

http_port: 80

tasks:

- name: apache2 package is present

apt:

name: apache2

state: latest

- name: latest index.html file is present

copy:

src: files/index.html

dest: /var/www/html/


Host Selector


---

- name: install and start apache

hosts: web

become: yes

vars:

http_port: 80

tasks:

- name: apache2 package is present

apt:

name: apache2

state: latest

- name: latest index.html file is present

copy:

src: files/index.html

dest: /var/www/html/


Privilege Escalation


---

- name: install and start apache

hosts: web

become: yes

vars:

http_port: 80

tasks:

- name: apache2 package is present

apt:

name: apache2

state: latest

- name: latest index.html file is present

copy:

src: files/index.html

dest: /var/www/html/


Play Variables:

---

- name: install and start apache

hosts: web

become: yes

vars:

http_port: 80

tasks:

- name: apache2 package is present

apt:

name: apache2

state: latest

- name: latest index.html file is present

copy:

src: files/index.html

dest: /var/www/html/


Tasks:

---

- name: install and start apache

hosts: web

become: yes

vars:

http_port: 80

tasks:

- name: latest apache2 package is present

apt:

name: apache2

state: latest

- name: latest index.html file is present

copy:

src: files/index.html

dest: /var/www/html/










































Load Balancing With NGINX

 Load Balancing with NGINX





First of all,

On the back end web servers, run the following command to Install NGINX:


$ sudo apt-get install -y  (-y means yes)

$ uname -n | sudo tee /usr/share/nginx/html/index.html


On the load balancer, run the follow commands:

$ sudo apt-get install nginx -y


Use the following as the contents of /etc/nginx/sites-available/default:


upstream web_backend {

# Uncomment for the IP Hashing load balancing method:

# ip_hash;

# Uncomment for the Least Connected load balancing method:

# least_conn;

# Replace the IP addresses with the IP addresses

# (or hostnames) of your back end web servers.

# Examples:

# server www1.example.com:8080;

# server 192.168.1.100;

server 10.11.12.51;

server 10.11.12.52;

}

server {

listen 80;

location / {

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_pass http://web_backend;

}

}


Make NGINX read the new conf by running the following command:

$ sudo service nginx reload





CMD Commands

All CMD Commands




 1. Accessibility Controls - access.cpl 

2. Accessibility Wizard - accwiz 

3. Add Hardware Wizard - hdwwiz.cpl 

4. Add/Remove Programs - appwiz.cpl 

5. Administrative Tools - control admintools 

6. Automatic Updates - wuaucpl.cpl 

7. Bluetooth Transfer Wizard - fsquirt 

8. Calculator - calc 

9. Certificate Manager - certmgr.msc 

10. Character Map - charmap 

11. Check Disk Utility - chkdsk 

12. Clipboard Viewer - clipbrd 

13. Command Prompt - cmd 

14. Component Services - dcomcnfg 

15. Computer Management - compmgmt.msc 

16. Control Panel - control 

17. Date and Time Properties - timedate.cpl 

18. DDE Shares - ddeshare 

19. Device Manager - devmgmt.msc 

20. Direct X Troubleshooter - dxdiag 

21. Disk Cleanup Utility - cleanmgr 

22. Disk Defragment - dfrg.msc 

23. Disk Management - diskmgmt.msc 

24. Disk Partition Manager - diskpart 

25. Display Properties - control desktop 

26. Display Properties - desk.cpl 

27. Dr. Watson System Troubleshooting Utility - drwtsn32 

28. Driver Verifier Utility - verifier 

29. Event Viewer - eventvwr.msc 

30. Files and Settings Transfer Tool - migwiz 

31. File Signature Verification Tool - sigverif 

32. Findfast - findfast.cpl 

33. Firefox - firefox 

34. Folders Properties - control folders 

35. Fonts - control fonts 

36. Fonts Folder - fonts 

37. Free Cell Card Game - freecell 

38. Game Controllers - joy.cpl 

39. Group Policy Editor (for xp professional) - gpedit.msc 

40. Hearts Card Game - mshearts 

41. Help and Support - helpctr 

42. HyperTerminal - hypertrm 

43. Iexpress Wizard - iexpress 

44. Indexing Service - ciadv.msc 

45. Internet Connection Wizard - icwconn1

46. Internet Explorer - iexplore 

47. Internet Properties - inetcpl.cpl 

48. Keyboard Properties - control keyboard 

49. Local Security Settings - secpol.msc 

50. Local Users and Groups - lusrmgr.msc 

51. Logs You Out Of Windows - logoff 

52. Malicious Software Removal Tool - mrt 

53. Microsoft Chat - winchat 

54. Microsoft Movie Maker - moviemk 

55. Microsoft Paint - mspaint 

56. Microsoft Syncronization Tool - mobsync 

57. Minesweeper Game - winmine 

58. Mouse Properties - control mouse 

59. Mouse Properties - main.cpl 

60. Netmeeting - conf 

61. Network Connections - control netconnections 

62. Network Connections - ncpa.cpl 

63. Network Setup Wizard - netsetup.cpl 

64. Notepad notepad 

65. Object Packager - packager 

66. ODBC Data Source Administrator - odbccp32.cpl 

67. On Screen Keyboard - osk 

68. Outlook Express - msimn 

69. Paint - pbrush 

70. Password Properties - password.cpl 

71. Performance Monitor - perfmon.msc 

72. Performance Monitor - perfmon 

73. Phone and Modem Options - telephon.cpl 

74. Phone Dialer - dialer 

75. Pinball Game - pinball 

76. Power Configuration - powercfg.cpl 

77. Printers and Faxes - control printers 

78. Printers Folder - printers 

79. Regional Settings - intl.cpl 

80. Registry Editor - regedit 

81. Registry Editor - regedit32 

82. Remote Access Phonebook - rasphone 

83. Remote Desktop - mstsc 

84. Removable Storage - ntmsmgr.msc 

85. Removable Storage Operator Requests - ntmsoprq.msc 

86. Resultant Set of Policy (for xp professional) - rsop.msc 

87. Scanners and Cameras - sticpl.cpl 

88. Scheduled Tasks - control schedtasks 

89. Security Center - wscui.cpl 

90. Services - services.msc 

91. Shared Folders - fsmgmt.msc 

92. Shuts Down Windows - shutdown 

93. Sounds and Audio - mmsys.cpl 

94. Spider Solitare Card Game - spider 

95. SQL Client Configuration - cliconfg 

96. System Configuration Editor - sysedit 

97. System Configuration Utility - msconfig 

98. System Information - msinfo32 

99. System Properties - sysdm.cpl

100. Task Manager - taskmgr 

101. TCP Tester - tcptest 

102. Telnet Client - telnet 

103. User Account Management - nusrmgr.cpl 

104. Utility Manager - utilman 

105. Windows Address Book - wab 

106. Windows Address Book Import Utility - wabmig 

107. Windows Explorer - explorer 

108. Windows Firewall - firewall.cpl 

109. Windows Magnifier - magnify 

110. Windows Management Infrastructure - wmimgmt.msc 

111. Windows Media Player - wmplayer 

112. Windows Messenger - msmsgs 

113. Windows System Security Tool - syskey 

114. Windows Update Launches - wupdmgr 

115. Windows Version - winver 

116. Windows XP Tour Wizard - tourstart 

117. Wordpad - write

Amazon Web Services Interview Questions




Q. Explain what is AWS?

A. AWS stands for Amazon Web Service; it is a collection of remote computing services also known as cloud computing platform. This new realm of cloud computing is also known as IaaS or Infrastructure as a Service.


Q. Mention what are the key components of AWS?
A. The key components of AWS are as follows:

Route 53: A DNS web service

Simple E-mail Service: It allows sending e-mail using RESTFUL API call or via regular             SMTP

Identity and Access Management: It provides enhanced security and identity                         management for your AWS account

Simple Storage Device or (S3): It is a storage device and the most widely used AWS                service

Elastic Compute Cloud (EC2): It provides on-demand computing resources for hosting             applications. It is very useful in case of unpredictable workloads

Elastic Block Store (EBS): It provides persistent storage volumes that attach to EC2                 to  allow you to persist data past the lifespan of a single EC2

CloudWatch: To monitor AWS resources, It allows administrators to view and collect             key Also, one can set a notification alarm in case of trouble. 


Q. Explain what is S3?

A. S3 stands for Simple Storage Service. You can use S3 interface to store and retrieve any amount of data, at any time and from anywhere on the web. For S3, the payment model is “pay as you go”.

Q. Explain what is AMI?

A. AMI stands for Amazon Machine Image. It’s a template that provides the information (an operating system, an application server, and applications) required to launch an instance, which is a copy of the AMI running as a virtual server in the cloud. You can launch instances from as many different AMIs as you need.

Q. Mention what is the relation between an instance and AMI?

A. From a single AMI, you can launch multiple types of instances. An instance type defines the hardware of the host computer used for your instance. Each instance type provides different compute and memory capabilities. Once you launch an instance, it looks like a traditional host, and we can interact with it as we would with any computer.


Q. What does an AMI include?

A. An AMI includes the following things

A template for the root volume for the instance
Launch permissions decide which AWS accounts can avail the AMI to launch instances
A block device mapping that determines the volumes to attach to the instance when it         is launched


Q. How can you send a request to Amazon S3?

A. Amazon S3 is a REST service, you can send a request by using the REST API or the AWS SDK wrapper libraries that wrap the underlying Amazon S3 REST API. 

Q. What is the Amazon EC2 service?

A. Amazon Elastic Compute Cloud (Amazon EC2) is a web service that provides resizable (scalable) computing capacity in the cloud. You can use Amazon EC2 to launch as many virtual servers you need. In Amazon EC2 you can configure security and networking as well as manage storage. Amazon EC2 service also helps in obtaining and configuring capacity using minimal friction

Q. What are the features of the Amazon EC2 service?

A. As the Amazon EC2 service is a cloud service so it has all the cloud features. Amazon EC2 provides the following features:

The virtual computing environment (known as instances)

Pre-configured templates for your instances (known as Amazon Machine Images –                 AMIs)

Amazon Machine Images (AMIs) is a complete package that you need for your server            (including the operating system and additional software)

Amazon EC2 provides various configurations of CPU, memory, storage and networking          capacity for your instances (known as instance type)

Secure login information for your instances using key pairs (AWS stores the public key            and you can store the private key in a secure place)

Storage volumes of temporary data are deleted when you stop or terminate your                 instance (known as instance store volumes)

Amazon EC2 provides persistent storage volumes (using Amazon Elastic Block Store –            EBS)

A firewall that enables you to specify the protocols, ports, and source IP ranges that an         reach your instances using security groups

Static IP addresses for dynamic cloud computing (known as Elastic IP address)

Amazon EC2 provides metadata (known as tags)

Amazon EC2 provides virtual networks that are logically isolated from the rest of the             AWS cloud, and that you can optionally connect to your own network (known as                     virtual private clouds – VPCs)


Q. What is the Amazon Machine Image (AMI)?

A. An Amazon Machine Image (AMI) is a template that contains a software configuration (for example, an operating system, an application server, and applications). From an AMI, we launch an instance, which is a copy of the AMI running as a virtual server in the cloud. We can even launch multiple instances of an AMI.

Q. What is the relation between Instance and AMI?

A. We can launch different types of instances from a single AMI. An instance type essentially determines the hardware of the host computer used for your instance. Each instance type offers different compute and memory capabilities.
After we launch an instance, it looks like a traditional host, and we can interact with it as we would do with any computer. We have complete control of our instances; we can use sudo to run commands that require root privileges

Q. Explain storage for Amazon EC2 instance?

A. Amazon EC2 provides many data storage options for your instances. Each option has a unique combination of performance and durability. These storages can be used independently or in combination to suit your requirements.
There are mainly four types of storage provided by AWS

Amazon EBS: Its durable, block-level storage volumes can attach to running Amazon EC2 instance. The Amazon EBS volume persists independently from the running life of an Amazon EC2 instance. After an EBS volume is attached to an instance, you can use it like any other physical hard drive. Amazon EBS encryption feature supports the encryption feature.

Amazon EC2 Instance Store: Storage disk that is attached to the host computer is referred to as instance store. The instance storage provides temporary block-level storage for Amazon EC2 instances. The data on an instance store volume persists only during the life of the associated Amazon EC2 instance; if you stop or terminate an instance, any data on instance store volumes is lost.

Amazon S3: Amazon S3 provides access to reliable and inexpensive data storage infrastructure. It is designed to make web-scale computing easier by enabling you to store and retrieve any amount of data, at any time, from within Amazon EC2 or anywhere on the web.

Adding Storage: Every time you launch an instance from an AMI, a root storage device is created for that instance. The root storage device contains all the information necessary to boot the instance. You can specify storage volumes in addition to the root device volume when you create an AMI or launch an instance using block device mapping.

Q. What is auto-scaling? How does it work?

A. Autoscaling is a feature of AWS which allows you to configure and automatically provision and spin up new instances without the need for your intervention. You do this by setting thresholds and metrics to monitor. When those thresholds are crossed, a new instance of your choosing will be spun up, configured, and rolled into the load balancer pool. Voila, you’ve scaled horizontally without any operator intervention!






GIT Cheat Sheet

Git Cheat Sheet (All Commands)






Git is the open source distributed version control system that facilitates GitHub activities on your laptop or desktop. This cheat sheet summarizes commonly used Git command line instructions for quick reference.


INSTALL GIT
GitHub provides desktop clients that include a graphical user
interface for the most common repository actions and an automatically
updating command line edition of Git for advanced scenarios.

GitHub for Windows
https://windows.github.com

GitHub for Mac
https://mac.github.com

Git distributions for Linux and POSIX systems are available on the
official Git SCM web site.

Git for All Platforms
http://git-scm.com


Git Configuration

Git Config

Get and set configuration variables that control all facets of how Git looks and operates.


Set the name:

$ git config --global user.name "User Name"


Set the email:

$ git config --global user.email "rootuser@gmail.com"


Set the default editor

$ git config --global core.editor vim


check the setting

$ git config -list


Git Alias

Set up an alias for each command:

$ git config --global alias.co checkout

$ git config --global alias.br branch

$ git config --global alias.ci commit

$ git config --global alias.st status


Starting a Project


Git init

Crate a repo

$ git init <repo name>

$ git clone <remote url>


Local Changes

Git add

Add a file to staging (index) area


$ git add filename

Add all files of a repo to staging (index) area

$ git add *


Git Commit

Record or snapshot the file permanently in the version history with a message.

$ git commit -m "msg"


Track Changes

Git diff

Track the changes that have not been changed:


$ git diff

Track the changes that have staged but not committed:


$ git diff --staged

Track the changes after commiting a file


$ git diff HEAD

Track the changes between two commit


$ git diff <commit1-sha> <commit2-sha>

Git diff branches:

$ git diff <branch1> <branch2>


Git Status

Display the state of the working directory and the staging are.


$ git status

Git show


show objects:

$ git show <option> <obj>


Commit History

Git log


Display the most recent commits and the status of the head:

$ git log


Display the output as one commit per line:

$ git log --oneline


Display the files that have been modified:

$ git log -stat


Display the modified files with location:

$ git log -p



Git Blame

Display the modification on each line of a file:

$ git blame <file name>


Ignoring files

.gitingore

specify intentionally untracked files that Git should ignore.

Create .gitignore:

$ touch .gitignore


List the ignores files:

$ git ls-files -i --exclude-standard


Branching

Git branch

Create branch

$ git branch <branch name>


List Branch: 

$ git branch --list


Delete Branch: 

$ git branch -d<branch name>


Delete a remote Branch:

 $ git push origin -delete <branch name>


Rename Branch: 

$ git branch -m <old branch name><new branch name>



Git checkout

Switch between branches in a repository.


Switch to a particular branch: 

$ git checkout <branch name>


Create a new branch and switch to it:

 $ git checkout -b <branchname>


Checkout a Remote branch: 

$ git checkout <remotebranch>


Git stash

Switch branches without committing the current branch.

Stash current work:


$ git stash

Saving stashes with a message: 

$ git stash save "<Stashing Message>"


Check the stored stashes: 

$ git stash list

Re-apply the changes that you just stashed 


$ git stash apply

Track the stashes and their changes: 

$ git stash show


Re-apply the previous commits:

 $ git stash pop


Delete a most recent stash from the queue: 

$ git stash drop


Delete all the available stashes at once: 

$ git stash clear


Stash work on a separate branch: 

$ git stash branch <branch name>


Merging

Git merge


Merge the branches: 

$ git merge <branch name>


Merge the specified commit to currently active branch:

 $ git merge <commit>


Git rebase

Apply a sequence of commits from distinct branches into a final commit. 

$ git rebase <branch name>


Continue the rebasing process: 

$ git rebase –continue


Abort the rebasing process:

 $ git rebase --skip


Git interactive rebase

Allow various operations like edit, rewrite, reorder, and more on existing commits.

 $ git rebase -i


Remote

Git remote


Check the configuration of the remote server: 

$ git remote -v


Add a remote for the repository: 

$ git remote add <short name><remote URL>


Fetch the data from remote server 

$ git fetch <Remote>


Remove a remote connection from the repository:

 $ git remote rm <destination>


Rename remote server: 

$ git remote rename <old name><new name>


Show additional information about a particular remote:

 $ git remote show <remote>


Change remote: 

$ git remote set-url <remote name><newURL>


Git origin master

Push data to remote server:

 $ git push origin master


Pull data from remote server: 

$ git pull origin master


Pushing Updates

Git push


Transfer the commits from your local repository to a remote server.


Push data to remote server: 

$ git push origin master


Force push data: 

$ git push <remote><branch> -f


Delete a remote branch by push command: 

$ git push origin -delete edited


Pulling updates

Git pull


Pull the data from the server: 

$ git pull origin master


Pull a remote branch: 

$ git pull <remote branch URL>


Git fetch

Downloads branches and tags from one or more repositories.


Fetch the remote repository:

 $ git fetch< repository Url>


Fetch a specific branch:

 $ git fetch <branch URL><branch name>


Fetch all the branches simultaneously: 

$ git fetch –all


Synchronize the local repository:

 $ git fetch origin


Undo changes

Git revert

Undo the changes 

$ git revert


Revert a particular commit: 

$ git revert <commit-ish>


Git reset

Reset the changes: $ git reset –hard $ git reset –soft $ git reset --mixed


Removing files

Git rm

Remove the files from the working tree and from the index:

$ git rm <file Name>


Remove files from the Git But keep the files in your local repository: $ git rm --cached






































Ansible Hands-on

  what is Ansible It's a simple automation language that can perfectly describe  an IT application infrastructure in Ansible Playbooks. ...