removed space from dir names

This commit is contained in:
2026-04-10 23:46:40 +03:30
parent d14e844a38
commit 9c419f72c4
25 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,84 @@
# **Ansible Configuration Guide**
Ansible is a powerful automation tool used to manage and configure servers. This guide provides examples of how to structure your inventory files, which are essential for defining the servers and groups that Ansible will manage. Additionally, it covers common Ansible commands for interacting with your servers.
## **Inventory File Examples**
### **INI Format**
The INI format is one of the simplest ways to define your inventory. Below are two examples showcasing different use cases.
#### **Example 1: Single Group Inventory**
In this example, all servers are grouped under a single `[all]` group. Each server is defined with specific connection details:
```ini
[all]
<server-name> ansible_host=<server-ip> ansible_ssh_pass=<password> ansible_port=<ssh-port> ansible_connection=<connection-type>
```
- **`<server-name>`**: A label or hostname for your server.
- **`<server-ip>`**: The IP address of the server.
- **`ansible_ssh_pass`**: The SSH password for connecting to the server.
- **`ansible_port`**: The port used for SSH connections.
- **`ansible_connection`**: The connection type (e.g., ssh, winrm).
#### **Example 2: Grouped Inventory with Variables**
This example demonstrates grouping servers by roles (e.g., `web`, `db`, `bk`). Group-specific variables are defined under `[all:vars]`:
```ini
[all]
<server1-name> ansible_host=<server1-ip>
<server2-name> ansible_host=<server2-ip>
<server3-name> ansible_host=<server3-ip>
[web]
<server1-name>
[db]
<server2-name>
[bk]
<server3-name>
[all:vars]
ansible_user=<username>
ansible_port=<ssh-port>
```
- **Groups**: Servers are organized into different groups (`web`, `db`, `bk`).
- **`[all:vars]`**: Common variables for all groups.
### **YAML Format**
The YAML format provides a more structured and readable way to define your inventory, especially useful for larger or more complex environments.
#### **Example: Grouped Inventory with Host-Specific Variables**
This example illustrates how to define an inventory with nested groups and host-specific variables:
```yaml
all:
children:
webservers:
hosts:
192.168.1.100:
ansible_port: 22
192.168.1.110:
ansible_port: 1357
vars:
http_port: 8080
dbserver:
hosts:
db.main.local:
db_user: admin
db_pass: secret
```
- **`children`**: Groups within the `all` group, such as `webservers` and `dbserver`.
- **`hosts`**: List of servers under each group, with their specific variables.
- **`vars`**: Group-specific variables, such as `http_port` for `webservers`.

View File

@@ -0,0 +1,106 @@
# **Ansible Commands**
Below are some frequently used Ansible commands for managing your servers.
### **Listing Hosts**
List all hosts defined in the inventory file:
```bash
ansible --list-hosts all -i servers.ini
# or for YAML format
ansible --list-hosts all -i servers.yaml
```
### **Ping All Servers**
Check the connectivity of all servers:
```bash
ansible -m ping all -i server.ini
```
### **Execute Commands**
Run a command (e.g., `uptime`) on all servers:
```bash
ansible -m command -a "uptime" all -i server.ini
```
### **Copy Files to Servers**
Copy a file from the Ansible server to all target servers:
```bash
ansible -m copy -a "src=<file-location-on-ansible-server> dest=<destination-location-on-server>" all -i server.ini
```
### **Run Commands with Sudo**
Execute a command with elevated privileges (sudo) as the root user:
```bash
ansible -m command -a "uptime" all -i server.ini --become --become-user root --become-method sudo
```
### **Install a Package**
Install the `nginx` package on all servers:
```bash
ansible -m apt -a "name=nginx state=present" --become --become-user root --become-method sudo
```
### **Uninstall a Package**
Remove the `nginx` package from all servers:
```bash
ansible -m apt -a "name=nginx state=absent" --become --become-user root --become-method sudo
```
### **Update and Upgrade Packages**
Update the package list and upgrade all packages:
```bash
ansible -m apt -a "upgrade=yes update_cache=yes" --become --become-user root --become-method sudo
```
---
## **Advanced Usage and Notes**
### **Special Considerations**
- **Module Limitations**: The `command` module does not support special characters or shell features. For commands requiring shell features (like pipes or redirection), use the `shell` module.
Example:
```bash
ansible -m shell -a "cat /etc/passwd | grep -l" all -i server.ini --become
```
- **Raw Module**: Use the `raw` module for devices that do not have Python installed. It allows you to execute raw SSH commands directly.
Example:
```bash
ansible -m raw -a "hostnamectl" all -i server.ini --become
```
### **Gathering System Facts**
Use the `setup` module to gather system facts from all servers:
```bash
ansible -m setup --become all -i server.ini
```
You can filter specific facts:
```bash
ansible -m setup -a "filter=ansible_memory" --become all -i server.ini
ansible -m setup -a "filter=ansible_distribution" --become all -i server.ini
```

View File

@@ -0,0 +1,374 @@
# Ansible Playbook Guide
Ansible Playbooks are YAML files that automate server configuration, deployment, and management tasks. This guide covers the basics of running a playbook, key concepts, and provides example playbooks to help you get started.
## Table of Contents
- [Ansible Playbook Guide](#ansible-playbook-guide)
- [Table of Contents](#table-of-contents)
- [Running an Ansible Playbook](#running-an-ansible-playbook)
- [Example](#example)
- [Key Concepts](#key-concepts)
- [Example Playbooks](#example-playbooks)
- [1. Simple APT Cache Update](#1-simple-apt-cache-update)
- [2. Update APT Cache and Install Nginx](#2-update-apt-cache-and-install-nginx)
- [3. Install Nginx and Copy Configuration File](#3-install-nginx-and-copy-configuration-file)
- [4. Full Nginx Deployment: Install, Configure, and Restart](#4-full-nginx-deployment-install-configure-and-restart)
- [5. Show Debug Message](#5-show-debug-message)
- [6. Use a Shell Command](#6-use-a-shell-command)
- [7. Playbook with Conditional Statements](#7-playbook-with-conditional-statements)
- [8. Check File Existence Using the `stat` Module](#8-check-file-existence-using-the-stat-module)
- [9. Standalone Nginx Installation](#9-standalone-nginx-installation)
- [10. Create a User](#10-create-a-user)
- [11. Install Multiple Packages](#11-install-multiple-packages)
- [Using a Loop](#using-a-loop)
- [Using a List](#using-a-list)
- [12. Create Multiple Users](#12-create-multiple-users)
- [13. Import Playbook Files](#13-import-playbook-files)
- [14. Remove `resolv.conf`](#14-remove-resolvconf)
- [15. Enable SSH Login Banner](#15-enable-ssh-login-banner)
---
## Running an Ansible Playbook
To run an Ansible playbook, use the following command:
```bash
ansible-playbook <playbook.yaml> -i <inventory-file.ini>
```
- **`<playbook.yaml>`**: The path to your playbook file.
- **`<inventory-file.ini>`**: The path to your inventory file (can be in INI or YAML format).
### Example
```bash
ansible-playbook deploy_nginx.yaml -i inventory.ini
```
This command runs the `deploy_nginx.yaml` playbook on the hosts defined in `inventory.ini`.
## Key Concepts
- **`hosts: all`**: Specifies the target hosts from the inventory on which the playbook should run.
- **`become: yes`**: Executes tasks with elevated privileges (sudo).
- **Handlers**: Special tasks triggered by other tasks using the `notify` directive.
- **Variables**: Dynamic values that can be reused across tasks and playbooks for flexibility and maintainability.
---
## Example Playbooks
### 1. Simple APT Cache Update
This playbook updates the APT package cache on all specified hosts.
```yaml
- name: Update APT Cache
hosts: all
become: yes
tasks:
- name: Update apt-cache
ansible.builtin.apt:
update_cache: yes
```
### 2. Update APT Cache and Install Nginx
This playbook updates the APT cache and installs the Nginx web server.
```yaml
- name: Update APT Cache and Install Nginx
hosts: all
become: yes
tasks:
- name: Update apt-cache and install Nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: yes
```
### 3. Install Nginx and Copy Configuration File
This playbook installs Nginx and copies a custom configuration file from the Ansible control node to the target hosts.
```yaml
- name: Install Nginx and Copy Configuration
hosts: all
become: yes
tasks:
- name: Update apt-cache and install Nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: yes
- name: Copy Nginx configuration file
ansible.builtin.copy:
src: /root/ansible/nginx.conf
dest: /etc/nginx/nginx.conf
```
### 4. Full Nginx Deployment: Install, Configure, and Restart
This playbook demonstrates a complete Nginx deployment, including installation, configuration, and restarting the service.
```yaml
- name: Full Nginx Deployment
hosts: all
become: yes
tasks:
- name: Update apt-cache and install Nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: yes
- name: Copy Nginx configuration file
ansible.builtin.copy:
src: /root/ansible/nginx.conf
dest: /etc/nginx/nginx.conf
notify: Restart Nginx
handlers:
- name: Restart Nginx
ansible.builtin.service:
name: nginx
state: restarted
```
### 5. Show Debug Message
Use the `debug` module to display a message during playbook execution. This is useful for testing or providing feedback within your playbooks.
```yaml
- name: Show Debug Message
hosts: all
tasks:
- name: Display debug message
ansible.builtin.debug:
msg: "Test Message"
```
### 6. Use a Shell Command
Run a shell command and capture the output for further use within the playbook.
```yaml
- name: Execute Shell Command
hosts: all
tasks:
- name: Run a shell command
ansible.builtin.shell:
cmd: echo "Hello, Ansible!"
register: shell_output
- name: Display Shell Output
ansible.builtin.debug:
msg: "Output is: {{ shell_output.stdout }}"
```
### 7. Playbook with Conditional Statements
This playbook demonstrates using conditional statements to check if a file exists and take action based on the result.
```yaml
- name: Check if File Exists
hosts: all
tasks:
- name: Check if file exists
ansible.builtin.shell:
cmd: ls /path/to/file
register: file_output
ignore_errors: yes
- name: File Exists
ansible.builtin.debug:
msg: "File exists"
when: file_output.rc == 0
- name: File Does Not Exist
ansible.builtin.debug:
msg: "File does not exist"
when: file_output.rc != 0
```
### 8. Check File Existence Using the `stat` Module
A more reliable method to check if a file exists using the `stat` module.
```yaml
- name: Check if File Exists
hosts: all
tasks:
- name: Check if file exists
ansible.builtin.stat:
path: /path/to/file
register: file_stat
- name: File Exists
ansible.builtin.debug:
msg: "File exists"
when: file_stat.stat.exists
- name: File Does Not Exist
ansible.builtin.debug:
msg: "File does not exist"
when: not file_stat.stat.exists
```
### 9. Standalone Nginx Installation
This playbook installs Nginx on both Debian-based and RedHat-based systems by detecting the operating system family.
```yaml
- name: Install Nginx
hosts: all
become: yes
tasks:
- name: Install on Debian-based systems
ansible.builtin.apt:
name: nginx
state: present
when: ansible_facts['os_family'] == "Debian"
- name: Install on RedHat-based systems
ansible.builtin.yum:
name: nginx
state: present
when: ansible_facts['os_family'] == "RedHat"
```
### 10. Create a User
This playbook checks if a user exists and creates the user if it does not.
```yaml
- name: Manage User Account
hosts: all
become: yes
tasks:
- name: Check if user exists
ansible.builtin.command:
cmd: id new_user
register: user_data
ignore_errors: yes
- name: Create user
ansible.builtin.user:
name: new_user
state: present
when: user_data.rc != 0
```
### 11. Install Multiple Packages
These examples show how to install multiple packages using either a loop or a list.
#### Using a Loop
```yaml
- name: Install Multiple Packages with Loop
hosts: all
become: yes
tasks:
- name: Install packages
ansible.builtin.apt:
name: "{{ item }}"
state: present
loop:
- vim
- git
- nginx
```
#### Using a List
```yaml
- name: Install Multiple Packages as a List
hosts: all
become
: yes
tasks:
- name: Install packages
ansible.builtin.apt:
name: ["vim", "nginx", "git"]
state: present
```
### 12. Create Multiple Users
This playbook creates multiple users with different groups.
```yaml
- name: Create Multiple Users
hosts: all
become: yes
tasks:
- name: Create users
ansible.builtin.user:
name: "{{ item.name }}"
group: "{{ item.group }}"
state: "{{ item.state }}"
loop:
- { name: "radin", state: "present", group: "sudo" }
- { name: "test", state: "present", group: "dev" }
- { name: "test2", state: "present", group: "test_unit" }
```
### 13. Import Playbook Files
You can split your playbooks into smaller, manageable files and include them as needed.
```yaml
- name: Nginx Setup
import_playbook: nginx.yaml
- name: User Creation
import_playbook: users.yaml
```
### 14. Remove `resolv.conf`
This playbook removes the `resolv.conf` file from all specified hosts.
```yaml
- name: Remove resolv.conf
hosts: all
become: yes
tasks:
- name: Remove resolv.conf
ansible.builtin.file:
path: /etc/resolv.conf
state: absent
ignore_errors: true # Ignore errors if the file does not exist
```
### 15. Enable SSH Login Banner
This playbook enables an SSH login banner by copying a banner file and updating the SSH configuration.
```yaml
- name: Enable SSH Login Banner
hosts: all
become: yes
tasks:
- name: Copy Banner
ansible.builtin.copy:
src: "issue.net"
dest: /etc/issue.net
ignore_errors: true # Ignore errors if the source file does not exist
- name: Update SSHD Config File for Banner
ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^Banner'
line: 'Banner /etc/issue.net'
- name: Restart SSH Service
ansible.builtin.service:
name: sshd
state: restarted
```

View File

@@ -0,0 +1,251 @@
# Ansible Roles and Directory Structure
Ansible roles help organize automation tasks, variables, files, and other resources into a structured format. This organization promotes reusability, simplifies management, and results in cleaner, more maintainable code.
## Creating a Role Directory Structure
To create a new Ansible role, use the following command:
```bash
ansible-galaxy init <role_name>
```
This command generates the standard directory structure for an Ansible role, which includes the following directories:
### Ansible Role Directory Breakdown
1. **`roles/`**: The top-level directory where all roles are stored. Each role has its own directory within this folder.
2. **`<role_name>/`**: Each role directory, named after the role (e.g., `webserver`), contains the following subdirectories:
- **`tasks/`**: Defines the list of tasks to be executed by the role, usually in a `main.yml` file.
- **`handlers/`**: Contains handlers that are triggered by tasks, defined in a `main.yml` file.
- **`defaults/`**: Holds default variables for the role in `defaults/main.yml`.
- **`vars/`**: Contains variables with higher precedence than `defaults`, stored in `vars/main.yml`.
- **`files/`**: Stores static files to be deployed to managed nodes.
- **`templates/`**: Holds Jinja2 templates for dynamic file generation.
- **`meta/`**: Contains metadata about the role, including dependencies.
- **`library/`** (Optional): Stores custom modules.
- **`module_utils/`** (Optional): Contains utilities for custom modules.
- **`lookup_plugins/`** (Optional): Holds custom lookup plugins.
- **`filter_plugins/`** (Optional): Stores custom filter plugins.
This structure ensures roles are well-organized, making them easier to share and reuse.
## Host-Specific Variables (`host_vars`)
`host_vars` define variables specific to individual hosts (managed nodes), allowing customization of configurations and behavior at the host level.
### Key Points:
- **Location**: `host_vars` is typically located at the same level as your inventory file or playbook.
- **Structure**: Inside `host_vars`, create files named after each host (e.g., `webserver1.example.com.yml`).
- **Precedence**: Variables in `host_vars` override group variables and defaults.
### Example:
```yaml
# host_vars/webserver1.example.com.yml
http_port: 8080
max_clients: 200
```
## Group-Specific Variables (`group_vars`)
`group_vars` define variables for groups of hosts, reducing repetition and enhancing organization when configuring multiple hosts with common settings.
### Key Points:
- **Location**: `group_vars` is typically located at the same level as your inventory file or playbook.
- **Structure**: Inside `group_vars`, create files named after each group (e.g., `webservers.yml`).
- **Precedence**: Variables in `group_vars` have a lower precedence than `host_vars` but higher than global variables.
### Example:
```yaml
# group_vars/dbservers.yml
db_port: 5432
db_user: "dbadmin"
```
## The `files` Directory in Ansible Roles
The `files` directory in an Ansible role stores static files that are copied to managed nodes.
### Usage:
- **Static Files**: Files that do not require modification before being transferred.
- **Task Example**:
```yaml
# roles/my_role/tasks/main.yml
- name: Copy a script to the target host
ansible.builtin.copy:
src: example_script.sh
dest: /usr/local/bin/example_script.sh
mode: '0755'
```
## The `templates` Directory in Ansible Roles
The `templates` directory stores Jinja2 templates, which are dynamically processed to create files on managed nodes.
### Example:
```yaml
# roles/my_role/tasks/main.yml
- name: Configure application
ansible.builtin.template:
src: my_config_file.conf.j2
dest: /etc/myapp/my_config_file.conf
```
### Sample Template:
```jinja
# my_config_file.conf.j2
server_name: {{ server_name_variable }}
{% if enable_feature %}
enable_feature: true
{% else %}
enable_feature: false
{% endif %}
{% for item in item_list %}
item_name: {{ item.name }}
item_value: {{ item.value }}
{% endfor %}
database_host: {{ database_host_variable | default('localhost') }}
```
## Handlers in Ansible Roles
Handlers are tasks triggered by other tasks, typically used to perform actions like restarting a service when a configuration change occurs.
### Example:
```yaml
# roles/my_role/tasks/main.yml
- name: Install apache2
ansible.builtin.apt:
name: apache2
state: present
notify: restart apache2
handlers:
- name: restart apache2
ansible.builtin.service:
name: apache2
state: restarted
```
## Default Variables in Ansible Roles (`defaults` Directory)
The `defaults` directory contains role-specific default variables with the lowest precedence, allowing them to be easily overridden.
### Example:
```yaml
# roles/my_role/defaults/main.yml
web_server_port: 80
max_clients: 100
```
## The `tasks` Directory in Ansible Roles
The `tasks` directory is where the main actions of a role are defined. It typically contains a `main.yml` file, which outlines the tasks Ansible should perform.
### Example:
```yaml
# roles/my_role/tasks/main.yml
- name: Include setup tasks
import_tasks: setup.yml
- name: Install required packages
import_tasks: install.yml
- name: Configure application
import_tasks: configure.yml
```
## Importing Roles in a Playbook
You can import multiple roles within a playbook as shown below:
```yaml
- hosts: all
roles:
- role: role1
- role: role2
- role: role3
gather_facts: yes
```
## Importing Other Tasks
In addition to roles, you can also include specific task files within a playbook:
```yaml
- name: Basic Setup
include_tasks: task_file.yaml
```
## Working with Tags
Tags allow you to run specific parts of your playbook or roles. They are useful when you want to execute only a subset of tasks.
### Example:
```yaml
- hosts: all
roles:
- role: role1
gather_facts: yes
tags: [install]
```
### Running Playbooks with Tags
```bash
ansible-playbook -i inventory.ini main.yml -t install
```
### Listing Tasks with Tags
To see which tasks will run under a specific tag, use:
```bash
ansible-playbook -i inventory.ini main.yml -t install --list-tasks
```
## Copying `resolv.conf` with a Jinja Template
Use a Jinja template to dynamically generate the `resolv.conf` file.
### Playbook:
```yaml
- name: Copy resolv.conf
ansible.builtin.template:
src: resolv.conf.j2
dest: /etc/resolv.conf
mode: 0644
```
### Jinja Template (`resolv.conf.j2`):
```jinja
nameserver {{ DNS1 }}
nameserver {{ DNS2 }}
```
### Group Variables (`group_vars`):
```yaml
# group_vars/all.yml
DNS1: 8.8.8.8
DNS2: 4.2.2.4
```

View File

@@ -0,0 +1,93 @@
## Ansible Vault Guide
### 1. Creating an Encrypted File with Ansible Vault
To create a new encrypted file using Ansible Vault, use the following command:
```bash
ansible-vault create secret.yaml
```
You will be prompted to enter a password to encrypt the file. After that, you can add your variables, like in the example below:
```yaml
password: 123
```
Once you save and exit, the file will be encrypted. The content of the `secret.yaml` file will look like this:
```yaml
$ANSIBLE_VAULT;1.1;AES256
33653733613264663235353662336132376134313266666561363932373236653130393135373562
3838613763626464343334306661643634323537376537630a333833356462616666303833613066
35653039343366336233613164313365373466643262303761623363383530396336613438326263
3536633236376635320a396430353564356331623133653866663138373265363466353663353034
3830
```
### 2. Using Encrypted Variables in a Playbook
To use the encrypted variables stored in `secret.yaml`, include the file in your playbook using `vars_files`.
#### Example Playbook
```yaml
- hosts: all
become: yes
vars_files:
- secret.yaml
tasks:
- name: Print Secret Password
debug:
msg: "Password is {{ password }}"
```
This playbook reads the encrypted `password` variable from `secret.yaml` and prints it.
### 3. Running the Playbook with Vault
To run a playbook that uses an encrypted file, use the following command:
```bash
ansible-playbook main.yaml -i servers.ini --ask-vault-pass --become
```
- **`--ask-vault-pass`**: Prompts for the Vault password before executing the playbook.
- **`--become`**: Ensures that the tasks are executed with elevated privileges (e.g., root).
When you run the command, you will be prompted to enter the Vault password to decrypt `secret.yaml` and access the `password` variable.
### 4. Additional Vault Commands
- **Edit an existing encrypted file**:
```bash
ansible-vault edit secret.yaml
```
- **Rekey (change the Vault password)**:
```bash
ansible-vault rekey secret.yaml
```
- **View the contents of an encrypted file (without decrypting it)**:
```bash
ansible-vault view secret.yaml
```
- **Decrypt a Vault file permanently**:
```bash
ansible-vault decrypt secret.yaml
```
- **Encrypt a previously unencrypted file**:
```bash
ansible-vault encrypt secret.yaml
```
Ansible Vault provides a powerful way to securely manage sensitive data in your automation processes.

View File

@@ -0,0 +1,19 @@
### Exit Codes Overview
Understanding exit codes is crucial when dealing with shell commands:
| Exit Code | Description |
|-----------|-----------------------------------------------|
| 0 | Success: The command completed successfully. |
| 1 | General error: Catchall for general errors. |
| 2 | Misuse of shell builtins (e.g., `cd`). |
| 126 | Command invoked cannot execute. |
| 127 | Command not found. |
| 128 | Invalid argument to exit. |
| 130 | Script terminated by Control-C. |
| 137 | Script terminated by `kill` (or OOM). |
| 139 | Segmentation fault. |
| 141 | Script terminated by `kill -13` (SIGPIPE). |
| 143 | Script terminated by `kill -15` (SIGTERM). |
| 255 | Exit status out of range (exceeds 255). |