Пример Terraform VPS + Ansible NGINX
Пример Terraform VPS + Ansible NGINX
Создаем с помощью terraform в Digital Ocean сервер, узнаем его ip и передаем в ansible для создания веб-сервера nginx
При этом с помощью ansible мы создадим динамические конфиги и наполнение отдаваемой страницы
Будут показаны примеры взаимодествия с шаблонами jinja2
Terraform
terraform.tfvars:
do_token="111"
aws_access_key = "222"
aws_secret_key = "333"
variables.tf:
variable "do_token" {}
variable "local_ssh_public_key" {
default = "~/.ssh/id_rsa.pub"
}
hosts.tmpl:
all:
hosts:
vps:
ansible_ssh_host: ${ipv4_address}
ansible_ssh_private_file: ~/.ssh/id_rsa
provider.tf:
terraform {
required_providers {
digitalocean = {
source = "digitalocean/digitalocean"
version = "~> 2.0"
}
}
}
provider "digitalocean" {
token = var.do_token
}
resources.tf:
resource "digitalocean_volume" "tv1" {
region = "nyc1"
name = "tv1"
size = 1
initial_filesystem_type = "ext4"
}
resource "digitalocean_ssh_key" "local_ssh_pkey" {
name = "local_ssh_public_key"
public_key = file(var.local_ssh_public_key)
}
resource "digitalocean_droplet" "foobar" {
name = "test-vps"
size = "s-1vcpu-1gb"
image = "ubuntu-20-04-x64"
region = "nyc1"
ssh_keys = [digitalocean_ssh_key.local_ssh_pkey.id]
volume_ids = [digitalocean_volume.tv1.id]
}
resource "local_file" "out" {
filename = "${path.module}/hosts.yml"
content = templatefile("${path.module}/hosts.tmpl",
{
ipv4_address = digitalocean_droplet.foobar.ipv4_address
}
)
}
Запуск сценария terraform:
# terraform plan
# terraform apply
В итоге мы создали vps и занесли ее ip в файл hosts.yml, который используем в ansible
hosts.yml:
all:
hosts:
vps:
ansible_ssh_host: 1.1.1.1
ansible_ssh_private_file: ~/.ssh/id_rsa
Ansible
В предыдущем шаге мы созданной vps прописали публичный ключ, значит ansible сможет к ней подключиться по ssh
Директория templates с шаблонами ansible
nginx.j2:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections {{ worker_connections }};
}
http {
gzip on;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
vhost.j2:
server {
listen 80;
root {{ item.documentroot }}/html/;
index index.htm;
server_name {{ item.servername }};
localtion / {
try_files $uri $uri/ =404;
}
}
index.j2:
Hello from {{ item.servername }}
Days of the week:
{% for item in days%}
{{ loop.index }} {{ item|upper }}
{% endfor %}
Файлы для ansible
ansible.cfg:
[defaults]
host_key_checking=false
vars.yml:
key: ~/.ssh/id_rsa
worker_connections: 512
days: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
nginx_vhosts:
- {servername: "site1.local", documentroot: "/www/site1.local"}
- {servername: "site2.local", documentroot: "/www/site2.local"}
a01.yml
- hosts:
- vps
vars_files:
- vars.yml
# vars:
# ansible_ssh_private_key_file: "{{ key }}"
become: true
tasks:
# - name: Echo uname
# command: uname -a
# register: result
# - name: Debug the output
# debug:
# var: result.stdout
# - name: Filter and return only selected facts
# ansible.builtin.setup:
# filter:
# - 'all_ipv4_addresses'
# debug:
# var: all_ipv4_addresses
# - name: ensure package cache is up to date
# become: true
# apt:
# upgrade: yes
# update_cache: yes
# cache_valid_time: 86400
- name: Install web server NGINX
apt:
name: nginx
state: present
update_cache: yes
- name: Enable and ensure is started NGINX service
service:
name: nginx
enabled: yes
state: started
- name: Copy nginx file
template:
src: nginx.j2
dest: /etc/nginx.conf
notify:
- reloaded nginx
- name: Create vhost files
template:
src: vhost.j2
dest: "/etc/nginx/sites-available/{{ item.servername }}.conf"
with_items: "{{ nginx_vhosts }}"
notify:
- reloaded nginx
- name: Create index.htm files
template:
src: index.j2
dest: "/www/{{ item.servername }}/html/index.htm"
with_items: "{{ nginx_vhosts }}"
- name: Create sylinks
file:
src: "/etc/nginx/sites-available/{{ item.servername }}.conf"
dest: "/etc/nginx/sites-enabled/{{ item.servername }}.conf"
state: link
with_items: "{{ nginx_vhosts }}"
notify:
- reloaded nginx
handlers:
- name: reloaded nginx
service:
name: nginx
state: reloaded
Запуск сценария ansible:
# ansible-playbook a01.yml -i hosts.yml --syntax-check
# ansible-playbook a01.yml -i hosts.yml
Итого, мы создали vps с вебсервером и динамически создаваемыми двумя виртуальными конфигами
В них применили циклы и переменные для динамического наполнения index файла
Комментарии пользователей
Анонимам нельзя оставоять комментарии, зарегистрируйтесь!