Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
2. Необходимо развернуть n количество ВМ с атрибутом прерываемый
2. Развернуть необходимые подсети
3. Создать публичный ssh ключ и приатачить к ВМ
4. Создать загружаемый диск с ubuntu 20.04
4. Создать загружаемый диск с ubuntu 22.04
5. Создать flavor 1CPU 2 gb RAM, Диск объем 10гб на каждую вм (базовый hdd)
6. Для каждой ВМ зафиксировать публичный ip адрес
7. В output зафиксировать вывод ip адрес и команду ssh для полключения
Expand Down
71 changes: 48 additions & 23 deletions ansible/docker-install/tasks/main.yml
Original file line number Diff line number Diff line change
@@ -1,42 +1,67 @@
---
# tasks file for docker-install
- name: Install aptitude
ansible.builtin.apt:
name: aptitude
state: latest
update_cache: true
#======================= BASIC PACKAGES ============================
- name: update apt list
apt:
update_cache: yes

- name: Install required system packages
- name: Install basic packages
ansible.builtin.apt:
pkg:
name:
- apt-transport-https
- ca-certificates
- curl
- software-properties-common
- python3
- python3-pip
- virtualenv
- python3-setuptools
state: latest
update_cache: true
state: present

#======================= GPG KEYS ============================


- name: Add Docker GPG apt Key
- name: Add Docker GPG key
ansible.builtin.apt_key:
url: https://download.docker.com/linux/ubuntu/gpg
state: present

- name: Add Docker Repository
#======================= ADD REPOS ============================

- name: Add Docker repository
ansible.builtin.apt_repository:
repo: deb https://download.docker.com/linux/ubuntu jammy stable
repo: 'deb [arch=amd64] https://download.docker.com/linux/ubuntu jammy stable'
state: present
update_cache: yes

#======================= INSTALL ADDITIONAL PACKAGES ============================

- name: Update apt and install docker-io
- name: Install additional packages
ansible.builtin.apt:
name: docker.io
state: latest
name:
- libc6
- docker-ce
- docker-ce-cli
- containerd.io
- docker-buildx-plugin
- docker-compose-plugin
state: present
update_cache: true

- name: Install Docker Compose
#- name: Install Docker Compose
# ansible.builtin.get_url:
# url: "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-{{ ansible_system | lower }}-{{ ansible_architecture }}"
# dest: /usr/local/bin/docker-compose
# mode: '0755'
#
- name: Install docker python packages
ansible.builtin.pip:
name:
- urllib3
- docker-compose
- docker==6.1.3.
- docker-compose==1.29.2
- requests==2.28.1
- urllib3==1.26.18
#
##======================= DOCKER ============================


- name: Enable and start Docker service
ansible.builtin.systemd:
name: docker
enabled: yes
state: started
2 changes: 1 addition & 1 deletion ansible/docker-service/tasks/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,5 @@
group: root

- name: Start containers
docker_compose:
community.docker.docker_compose:
project_src: /opt/service/compose
Binary file added assets/net1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/ping.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/todo_app.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 13 additions & 0 deletions forVM/inventory.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[db]
server ansible_host=192.168.56.11 ansible_user=me2

[app]
client ansible_host=192.168.56.12 ansible_user=me3

[db:vars]
ansible_ssh_private_key_file=/home/me1/.ssh/id_ed25519
ansible_become=true

[app:vars]
ansible_ssh_private_key_file=/home/me1/.ssh/id_ed25519
ansible_become=true
9 changes: 9 additions & 0 deletions forVM/playbook.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
- hosts: db
become: yes
roles:
- mysql

- hosts: app
become: yes
roles:
- todo
28 changes: 28 additions & 0 deletions forVM/roles/mysql/tasks/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
- name: Install pip for Python3
apt:
name: python3-pip
state: present
update_cache: true

- name: Install Docker Python module
pip:
name: docker
executable: pip3

- name: Install Docker
apt:
name: docker.io
state: present
update_cache: true

- name: Start MySQL container
docker_container:
name: mysql
image: mysql:5.7
state: started
restart_policy: always
ports:
- "3306:3306"
env:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: todos
36 changes: 36 additions & 0 deletions forVM/roles/todo/tasks/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
- name: Install pip for Python3
apt:
name: python3-pip
state: present
update_cache: true

- name: Install Docker Python module
pip:
name: docker
executable: pip3

- name: Install Docker
apt:
name: docker.io
state: present
update_cache: true

- name: Download Docker-image of todo-app
docker_image:
name: antonaleks/101-todo-app
tag: latest
source: pull

- name: Start todo-app container
docker_container:
name: todo
image: antonaleks/101-todo-app:latest
state: started
restart_policy: always
ports:
- "3000:80"
env:
DB_HOST: 192.168.56.11
DB_USER: root
DB_PASSWORD: password
DB_NAME: todos
2 changes: 1 addition & 1 deletion preemptible_server/vars.tf
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ variable "server_volume_type" {
}

variable "server_image_name" {
default = "Ubuntu 20.04 LTS 64-bit"
default = "Ubuntu 22.04 LTS 64-bit"
}

variable "server_preemptible_tag" {
Expand Down
137 changes: 137 additions & 0 deletions report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# Отчёт по работе №3: Практика Ansible

## Подготовка ВМ
1. Как и в прошлых работах создаём 3 ВМ для работы.
2. Как и в прошлых работах меняем на них hostname и user для удобства.
3. Меняем настройки сетевых адаптеров:
- на каждой машине оставляем **NAT** для выхода в сеть
- на каждой машине добавляем **Host-Only** адаптер
4. Через `netplan` задаём новые статические IP-адреса с одной подсетью для **Host-Only** адаптеров. По итогу имеем:
- Машина A: `me1@192.168.56.10` - хост с **Ansible**
- Машина B: `me2@192.168.56.11` - сервер для **MySQL**
- Машина C: `me3@192.168.56.12` - клиент с **ToDo**
Пример настроенной сети с машины A:

![netA](assets/net1.png)

5. После настройки сети устанавливаем между машинами **SSH-соединение**:
```shell
ssh-keygen -t ed25519 -C "ansible"
ssh-copy-id -i ~/.ssh/id_ed25519.pub me2@192.168.56.11
ssh-copy-id -i ~/.ssh/id_ed25519.pub me3@192.168.56.12
```
6. Проверяем **SSH-соединение** c хоста. Теперь можно установить ansible:
```shell
sudo apt update
sudo apt install ansible -y
```

## Настройка Ansible
1. Возьмём стандартную и рекомендуемую Ansible-структуру. В корневой папке проекта будет `ini` файл вместе с плейбуком и папка с ролями. Плейбук в свою очередь вызывает роли. В каждой роли (**todo** и **mysql**) будет свой `yml` файл с задачами (в папке **tasks**). Для удобства создаём все необходимые файлы локально, а затем копируем их через `scp` на хост с **Ansible**. *Папка проекта находится в репозитории под названием /forVM*. <br>

Структура проекта имеет вид:
```shell
forVM/
├── inventory.ini # инвентори-файл с IP/хостами
├── playbook.yml # основной плейбук, вызывает роли
└── roles/
├── mysql/
│ └── tasks/
│ └── main.yml # задачи для установки и запуска MySQL
└── todo/
└── tasks/
└── main.yml # задачи для todo-приложения
```

2. Определяем в плейбуке роли (**todo** и **mysql**) и создаём **tasks** для каждой из них. <br>
Задачи включают в себя установку необходимых зависимостей и запуск образов с выставленными env-переменными:

- **MySQL**:
```shell
- name: Install pip for Python3
apt:
name: python3-pip
state: present
update_cache: true

- name: Install Docker Python module
pip:
name: docker
executable: pip3

- name: Install Docker
apt:
name: docker.io
state: present
update_cache: true

- name: Start MySQL container
docker_container:
name: mysql
image: mysql:5.7
state: started
restart_policy: always
ports:
- "3306:3306"
env:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: todos
```

- **ToDo**:
```shell
- name: Install pip for Python3
apt:
name: python3-pip
state: present
update_cache: true

- name: Install Docker Python module
pip:
name: docker
executable: pip3

- name: Install Docker
apt:
name: docker.io
state: present
update_cache: true

- name: Download Docker-image of todo-app
docker_image:
name: antonaleks/101-todo-app
tag: latest
source: pull

- name: Start todo-app container
docker_container:
name: todo
image: antonaleks/101-todo-app:latest
state: started
restart_policy: always
ports:
- "3000:80"
env:
DB_HOST: 192.168.56.11
DB_USER: root
DB_PASSWORD: password
DB_NAME: todos
```

3. Пересылаем папку на машину А:
```shell
scp -r "/c/Users/user/Documents/Education/Clouds/CloudPractice/forVM" me1@192.168.56.10:/home/me1/
```
4. Пробуем пропинговать машины B и C. Получаем в ответ `pong`, значит все настроено верно:

![pong](assets/ping.png)

## Тестирование и результаты

1. Запускаем **playbook** на машине A. Во время установки всех файлов не должно быть ошибок.
2. Перейдем к проверке **ToDo** приложения, перейдя по адресу: http://192.168.56.12:3000/

![pong](assets/todo_app.png)

Представленные скриншоты подтверждают работоспособность системы.
Все необходимые файлы приложены в репозитории.