Ansible

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Ansible

Ansible is an open-source automation tool that allows you to automate tasks such as
configuration management, application deployment, and task orchestration on multiple servers.
Here are some key concepts related to Ansible:
1. **Agentless**:
- Ansible is agentless, which means it doesn't require any software or agents to be installed on
the managed nodes (servers you want to manage). It uses SSH (Secure Shell) to connect to the
nodes and perform tasks.
2. **SSH Connection**:
- Ansible uses SSH for secure communication between the control node (the machine where
Ansible is installed and from which you run Ansible commands) and the managed nodes.
3. **Inventory**:
- An inventory file (often named `inventory` or `hosts`) lists the managed nodes you want to
automate. It can be a simple text file or a dynamic script that generates the list. The inventory file
also allows you to group nodes for easier management.
4. **Control Node**:
- The control node is the machine where Ansible is installed. It's the system from which you
manage and execute Ansible commands and playbooks.
5. **Managed Node**:
- A managed node is a remote server or device that Ansible manages. These are the servers you
want to automate tasks on. Ansible connects to managed nodes via SSH.
6. **Modules**:
- Ansible modules are small programs that Ansible uses to perform tasks on managed nodes.
Each module is responsible for a specific type of task, such as installing a package, copying files,
or starting a service. Modules are executed on the managed nodes and report back to the control
node.
7. **Playbook**:
- A playbook is a YAML file that defines a set of tasks to be executed on the managed nodes.
Playbooks are used for automation and orchestration. They can include multiple tasks, variables,
and even conditionals.
8. **Tasks**:
- A task is a single action to be performed on a managed node. It can be as simple as copying a
file, or more complex like installing software or configuring services.
9. **Roles**:
- Roles provide a way to organize playbooks and share them across different projects. A role
includes tasks, variables, and templates in a defined structure. Roles make it easier to manage
and reuse configurations.
10. **Handlers**:
- Handlers are special tasks that are only executed if a task notifies them. They are typically
used to restart services or perform other actions that should only happen if a change has been
made.
11. **Modules and Facts**:
- Modules provide the functionality to carry out tasks, while facts are information about the
managed nodes. Ansible gathers facts about the managed nodes before executing tasks. Facts can
be used in playbooks to make them dynamic and adaptable.
12. **Idempotence**:
- Ansible is designed to be idempotent, meaning if a task is executed multiple times, it will
have the same effect as if it were executed once. This ensures that running playbooks multiple
times won't cause unintended side effects.

Setup Ansible in Control Node


To install Ansible on Ubuntu, you can use the following steps:
1. **Update Package Lists**:
Open a terminal window and run the following command to update the package lists:
```bash
sudo apt-get update
```
2. **Install Ansible**:
Once the package lists are updated, you can install Ansible by running the following command:
```bash
sudo apt-get install ansible
```
You'll be prompted to confirm the installation. Press `Y` to proceed.
3. **Verify Installation**:
After the installation is complete, you can verify if Ansible was installed correctly by checking
its version:
```bash
ansible --version
```
Setup SSH connection between Control Nodes & Managed Nodes
Step 3: Generate SSH Key Pair (On Control Node)
```bash
ssh-keygen
```
Step 4: Copy Public Key (On Control Node)
- Navigate to `/root/.ssh`
- View the public key with:
```bash
cat id_rsa.pub
```
- Copy the displayed public key.
Step 5: Paste Public Key (On Managed Nodes)
- Go to each managed node (e.g., node1, node2)
- Navigate to `/root/.ssh`
- Open or create the `authorized_keys` file and paste the public key.
Step 6: Set Permissions (On Managed Nodes)
```bash
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
```
You have now installed Ansible on your control node and set up SSH key-based authentication
between the control node and managed nodes. This allows Ansible to communicate securely
without the need for passwords.
step 7: Add IP in /etc/hosts file
```bash
vi /etc/ansible/hosts

[webservers]
IP1 ansible_ssh_private_key_file=~/.ssh/id_rsa ansible_user=root
IP2 ansible_ssh_private_key_file=~/.ssh/id_rsa ansible_user=root

[dbservers]
IP3 ansible_ssh_private_key_file=~/.ssh/id_rsa ansible_user=root
IP4 ansible_ssh_private_key_file=~/.ssh/id_rsa ansible_user=root
```
Ansible ad-hoc commands that you can use for various tasks:
1. **Ping all hosts**:
```bash
ansible all -m ping
```
This checks if all hosts in your inventory file are reachable.
2. **Get system information**:
```bash
ansible all -m setup
```
This command gathers facts about remote hosts. It provides detailed information about the
system.
3. **Update package cache**:
```bash
ansible all -m apt -a "update_cache=yes"
```
This updates the package cache on Debian-based systems.
4. **Install a package**:
```bash
ansible all -m apt -a "name=package_name state=present"
```
This installs a package on Debian-based systems. Replace `package_name` with the actual
package name.
5. **Restart a service**:
```bash
ansible all -m service -a "name=service_name state=restarted"
```
This restarts a service. Replace `service_name` with the actual service name.
6. **Create a directory**:
```bash
ansible all -m file -a "path=/path/to/directory state=directory"
```
This creates a directory on remote hosts.
7. **Copy a file to remote hosts**:
```bash
ansible all -m copy -a "src=/local/path/to/file dest=/remote/path/"
This copies a file from the control node to remote hosts.
8. **Execute a shell command**:
---
bash
ansible all -m shell -a "command"
Replace `command` with the actual shell command you want to execute.
9. **Set up a cron job**:
```bash
ansible all -m cron -a "name=job_name minute=30 hour=2 job='/path/to/script.sh'"
```
This sets up a cron job on the remote hosts.
10. **Check free disk space**:
```bash
ansible all -m command -a "df -h"
```

An Ansible playbook is a file or a set of files that contain a series of tasks that need to be
executed on one or more remote hosts. Playbooks are written in YAML format and are used to
automate configuration, deployment, and management tasks using Ansible.

A typical Ansible playbook includes the following elements:

1. Name: A descriptive name for the playbook. This is a human-readable label that helps
identify the purpose of the playbook.

2. Hosts: Specifies the target hosts or groups of hosts where the tasks in the playbook will
be executed.

3. Become: Defines whether to escalate privileges on the remote host, typically to perform
tasks that require administrative permissions.

4. Tasks: Contains a list of tasks to be executed on the target hosts. Each task consists of a
name, module name, and module-specific parameters.

o Name: A descriptive label for the task.


o Module: Specifies the Ansible module to use for the task (e.g., apt, copy, service,
etc.).
o Module Options: Parameters specific to the chosen module, which define the
behavior of the task.

Here's an example of a simple Ansible playbook that installs the Apache web server on a group
of hosts:

---
- name: Install Apache
hosts: web_servers
become: yes

tasks:
- name: Update package cache
apt:
update_cache: yes

- name: Install Apache


apt:
name: apache2
state: present
In this example:

 Name: "Install Apache" is the name of the playbook.


 Hosts: The playbook targets hosts in the group named web_servers.
 Become: It's set to yes, indicating that the tasks will be executed with escalated
privileges.
 Tasks: There are two tasks defined:
o The first task updates the package cache using the apt module.
o The second task installs the Apache web server using the apt module with specific
parameters.

You can save this playbook in a YAML file (e.g., install_apache.yml) and run it using
the ansible-playbook command:
ansible-playbook install_apache.yml
This will execute the tasks defined in the playbook on the specified hosts.

Sample Playbook-1 from Video

---
- name: webserver configuration
hosts: webservers
become: yes
tasks:
- name: update package cache
apt:
update_cache: yes

- name: Install Apache


apt:
name: apache2
state: present
- name: Install Maven
apt:
name: maven
state: present

- name: Database server configuration


hosts: dbservers
become: yes
tasks:
- name: install postgressql
apt:
name: postgresql
state: present
The provided text is an Ansible playbook written in YAML format. It defines a set of tasks to be
executed on two groups of hosts: webservers and dbservers. Let's break down the playbook:

1. Playbook Structure:

o ---: This denotes the start of a YAML document.


o The document contains two plays (sections), each specifying a different set of
hosts and tasks.

2. First Play:

o Name: "webserver configuration" is a label that describes the purpose of this


play.

o Hosts: This play targets hosts belonging to the group webservers.


o Become: It's set to yes, indicating that the tasks will be executed with escalated
privileges.

o Tasks:

 Task 1: "update package cache"

 Module: apt
 Module Options:
 update_cache: yes: Instructs apt to update the package
cache.
 Task 2: "Install Apache"

 Module: apt
 Module Options:
 name: apache2: Specifies the name of the package to
install.
 state: present: Ensures that the package is present
(installed).

 Task 3: "Install Maven"

 Module: apt
 Module Options:
 name: maven: Specifies the name of the package to install.
 state: present: Ensures that the package is present
(installed).

3. Second Play:

o Name: "Database server configuration"

o Hosts: This play targets hosts belonging to the group dbservers.


o Become: It's set to yes, indicating that the tasks will be executed with escalated
privileges.

o Tasks:

 Task 4: "install PostgreSQL"


 Module: apt
 Module Options:
 name: postgresql: Specifies the name of the package to
install.
 state: present: Ensures that the package is present
(installed).

Explanation:

 This playbook is designed to configure two types of servers: web servers and database
servers.

 For web servers (webservers group):


o It updates the package cache.
o Installs Apache and Maven if they are not already present.
 For database servers (dbservers group):
o It installs PostgreSQL if it is not already present.
 The become: yes setting allows the tasks to be executed with administrative privileges,
which may be necessary for tasks like installing packages.
You can run this playbook using the ansible-playbook command, specifying the playbook file's
location. For example:
ansible-playbook your_playbook.yml

Simple Build & Deploy Playbook


---
- name: webserver configuration
hosts: webservers
become: yes
tasks:
- name: update package cache
apt:
update_cache: yes

- name: Install Maven


apt:
name: maven
state: present
- name: Copy the Application to webserver
synchronize:
src: /home/ubuntu/BoardgameListingWebApp
dest: /home/ubuntu/

- name: Build & Deploy


hosts: webservers
become: yes
tasks:
- name: Build the Application
shell: |
cd /home/ubuntu/BoardgameListingWebApp
mvn package
- name: Deploy The Application
shell: |
cd /home/ubuntu/BoardgameListingWebApp/target
nohup java -jar *.jar &
This Ansible playbook is designed to configure and deploy a web application on a group of hosts
labeled as webservers. It consists of two plays:

Play 1: Webserver Configuration

 Name: "webserver configuration" is a label that describes the purpose of this play.
 Hosts: This play targets hosts belonging to the group webservers.
 Become: It's set to yes, indicating that the tasks will be executed with escalated
privileges.

Tasks:

1. Task 1: "update package cache"


Module: apt
o
Module Options:
o
 update_cache: yes: This instructs apt to update the package cache.
2. Task 2: "Install Maven"

o Module: apt
o Module Options:
 name: maven: Specifies the name of the package to install.
 state: present: Ensures that the package is present (installed).

3. Task 3: "Copy the Application to webserver"

o Module: synchronize
o Module Options:
 src: Specifies the source directory
(/home/ubuntu/BoardgameListingWebApp) on the control machine.
 dest: Specifies the destination directory (/home/ubuntu/) on the target host.

Play 2: Build & Deploy

 Name: "Build & Deploy"


 Hosts: This play targets hosts belonging to the group webservers.
 Become: It's set to yes, indicating that the tasks will be executed with escalated
privileges.

Tasks:

1. Task 4: "Build the Application"

o Module: shell
o Task Description: This task navigates to the application
directory, /home/ubuntu/BoardgameListingWebApp, and runs the Maven
command mvn package to build the application.

2. Task 5: "Deploy The Application"

o Module: shell
o Task Description: This task navigates to the target
directory, /home/ubuntu/BoardgameListingWebApp/target, and runs the
command nohup java -jar *.jar & to execute the application in the background.

Explanation:

 This playbook automates the deployment process of a web application.


 The first play sets up the necessary environment on the target servers by updating the
package cache, installing Maven, and copying the application files to the server.
 The second play focuses on building and deploying the application. It uses shell
commands to navigate to the application directory, build it using Maven, and then deploy
it using java -jar.

You can run this playbook using the ansible-playbook command, specifying the playbook file's
location:

ansible-playbook your_playbook.yml

Script
Sure! Here is your Ansible playbook converted to Markdown (md) format:

- name: Install java and net-tools


hosts: servers
tasks:
- name: Update apt repo and cache
ansible.builtin.apt: update_cache=yes force_apt_get=yes cache_valid_time=3600
- name: Install Java 8
ansible.builtin.apt: name=openjdk-8-jre-headless
- name: Install net-tools
ansible.builtin.apt: name=net-tools

- name: Download and unpack Nexus installer


hosts: servers
tasks:
- name: Check nexus folder stats
ansible.builtin.stat:
path: /opt/nexus
register: stat_result
- name: Download Nexus
ansible.builtin.get_url:
url: https://download.sonatype.com/nexus/3/nexus-3.60.0-02-unix.tar.gz
dest: /opt/
register: download_result
- name: Untar nexus installer
ansible.builtin.unarchive:
src: "{{download_result.dest}}"
dest: /opt/
remote_src: yes
when: not stat_result.stat.exists
- name: Find nexus folder
ansible.builtin.find:
paths: /opt
pattern: "nexus-*"
file_type: directory
register: find_result
- name: Rename nexus folder
command: mv /opt/nexus-3.60.0-02 /opt/nexus
when: not stat_result.stat.exists

- name: Create nexus user to own nexus folders


hosts: servers
tasks:
- name: Ensure group nexus exists
ansible.builtin.group:
name: nexus
state: present
- name: Create nexus user
ansible.builtin.user:
name: nexus
group: nexus
- name: Make nexus user owner of nexus folder
ansible.builtin.file:
path: /opt/nexus
state: directory
owner: nexus
group: nexus
recurse: yes
- name: Make nexus user owner of sonatype-work folder
ansible.builtin.file:
path: /opt/sonatype-work
state: directory
owner: nexus
group: nexus
recurse: yes

- name: Start nexus with nexus user


hosts: servers
become: True
become_user: nexus
tasks:
- name: Set run_as_user nexus
ansible.builtin.lineinfile:
path: /opt/nexus/bin/nexus.rc
regexp: '^#run_as_user=""'
line: run_as_user="nexus"
- name: Start nexus
command: /opt/nexus/bin/nexus start
Verify Nexus | Some Issue so run till previous stage

- name: Verify Nexus


hosts: servers
tasks:
- name: Check Nexus process status
ansible.builtin.shell: ps aux | grep nexus
register: app_status
- ansible.builtin.debug: msg={{ app_status.stdout_lines }}
- name: Wait for a minute
ansible.builtin.pause:
minutes: 2
- name: Check netstat
ansible.builtin.shell: netstat -plnt
register: netstat_result
- ansible.builtin.debug: msg={{ netstat_result.stdout_lines }}

You might also like