Образовательный проект «SnakeProject» Михаила Козлова

Навигация

⇒ FreeBSD and Nix ⇐

CISCO

Voice(Asterisk\Cisco)

Microsoft

Powershell

Python

SQL\T-SQL

Общая

WEB Разработка

ORACLE SQL \ JAVA

Мото

Стрельба, пневматика, оружие

Саморазвитие и психология


Пример запуска ansible из terraform


Пример запуска ansible из terraform
 
Не буду расшифровывать т.к. уже написан целый цикл статей на сайте
 
Тут терраформом поднимается 2 машины с nginx и вызывается ansible с помощью provisioner "local-exec"
Иден настрока одного проксирующего балансера nginx на второй
 
variables.tf
variable "do_token" {}
variable "aws_access_key" {}
variable "aws_secret_key" {}
variable "aws_region" {
  default = "eu-west-1"
}
variable "instance_count" {
  default = "2"
}
variable "local_ssh_public_key" {
    default     = "~/.ssh/id_rsa.pub"
}
variable "local_ssh_private_key" {
    default     = "~/.ssh/id_rsa"
}
variable "devs" {
  description = "Settings"
  type        = map(any)
  default     = {
    your_login  = "my_name",
    general_domain = "domain.ru"
  }
}
 
 
provider.tf
terraform {
  required_providers {
    digitalocean = {
      source = "digitalocean/digitalocean"
      version = "~> 2.0"
    }
  }
}
provider "digitalocean" {
  token = var.do_token
}
provider "aws" {
    access_key  = var.aws_access_key
    secret_key  = var.aws_secret_key
    region = var.aws_region
}
 
 
resources.tf
resource "digitalocean_volume" "vol_name" {
  count                   = var.instance_count
  region                  = "nyc1"
  name                    = "vol-${count.index + 1}"
  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   = "serv-${count.index + 1}"
  count  = var.instance_count
  size   = "s-1vcpu-1gb"
  image  = "ubuntu-20-04-x64"
  region = "nyc1"
  ssh_keys   = [digitalocean_ssh_key.local_ssh_pkey.id]
  volume_ids = ["${element(digitalocean_volume.vol_name.*.id, count.index)}"]
}
locals {
  vps_ip = digitalocean_droplet.foobar[*].ipv4_address
}
data "aws_route53_zone" "zone" {
  name = var.devs.general_domain
}
resource "aws_route53_record" "record" {
  zone_id = data.aws_route53_zone.zone.id
  name    = var.devs.your_login
  allow_overwrite = true
  type    = "A"
  ttl     = "300"
  records = [digitalocean_droplet.foobar[0].ipv4_address]
}
resource "local_file" "hosts" {
  filename = "${path.module}/hosts.yml"
  content = templatefile("${path.module}/hosts.tmpl",
    {
      droplets = digitalocean_droplet.foobar
    }
  )
}
resource "local_file" "vars" {
  filename = "${path.module}/roles/nginx/vars/main.yml"
  content = templatefile("${path.module}/vars.tmpl",
    {
      domain = "${var.devs.your_login}.${var.devs.general_domain}"
    }
  )
}
resource "local_file" "vhost_front" {
  filename = "${path.module}/roles/nginx_conf/templates/vhost_front.j2"
  content = templatefile("${path.module}/vhost_front.tmpl",
    {
      ip_addr_back = digitalocean_droplet.foobar[1].ipv4_address
    }
  )
}
resource "local_file" "nginx_conf_task_file" {
  filename = "${path.module}/roles/nginx_conf/tasks/main.yml"
  content = templatefile("${path.module}/main.tmpl",
    {
      hostname_front = digitalocean_droplet.foobar[0].name
      hostname_back = digitalocean_droplet.foobar[1].name
    }
  )
  provisioner "local-exec" {
    command = "ANSIBLE_CONFIG=${path.module}/ansible.cfg ansible-playbook playbook.yaml -i hosts.yml"
  }
}
 
 
hosts.tmpl
all:
  hosts:
%{ for droplet in droplets ~}
    ${droplet.name}:
      ansible_ssh_host: ${droplet.ipv4_address}
      ansible_ssh_private_key_file: /root/.ssh/id_rsa
      ansible_ssh_public_key_file: /root/.ssh/id_rsa.pub
%{ endfor }
 
 
main.tmpl
---
- name: Copy nginx file
  template:
    src: nginx.j2
    dest: /etc/nginx.conf
  notify:
    - reloaded nginx
  when: ansible_hostname == "${ hostname_front }"
- name: Copy certs
  copy:
    src: "./{{ ssl_certificate }}"
    dest: "/var/lib/certs/{{ item.servername }}/{{ ssl_certificate }}"
  with_items: "{{ nginx_vhosts }}"
  when: ansible_hostname == "${ hostname_front }"
- name: Copy certs key
  copy:
    src: "./{{ ssl_certificate_key }}"
    dest: "/var/lib/certs/{{ item.servername }}/{{ ssl_certificate_key }}"
  with_items: "{{ nginx_vhosts }}"
  when: ansible_hostname == "${ hostname_front }"
- name: Create vhost files front
  template:
    src: vhost_front.j2
    dest: "/etc/nginx/sites-available/{{ item.servername }}.conf"
  with_items: "{{ nginx_vhosts }}"
  when: ansible_hostname == "${ hostname_front }"
  notify:
    - reloaded nginx
- name: Create symlink vhost on front
  file:
    src: "/etc/nginx/sites-available/{{ item.servername }}.conf"
    dest: "/etc/nginx/sites-enabled/{{ item.servername }}.conf"
    state: link
    force: true
  when: ansible_hostname == "${ hostname_front }"
  with_items: "{{ nginx_vhosts }}"
  notify:
    - reloaded nginx
- name: Create vhost files back
  template:
    src: vhost_back.j2
    dest: "/etc/nginx/sites-enabled/default"
  when: ansible_hostname == "${ hostname_back }"
  notify:
    - reloaded nginx
- name: Create index.htm files
  template:
    src: index.j2
    dest: "/var/www/html/index.htm"
  with_items: "{{ nginx_vhosts }}"
  when: ansible_hostname == "${ hostname_back }"
 
 
vars.tmpl
---
# vars file for nginx
keys: 
    - { src: ./id_rsa, dest: /root/.ssh/ }
    - { src: ./id_rsa.pub, dest: /root/.ssh/ }
ssl_certificate: ./nginx-selfsigned.crt
ssl_certificate_key: nginx-selfsigned.key
worker_connections: 768
sendfile: on
tcp_nodelay: on
tcp_nopush: on
days: ['1', '2', '3', '4', '5', '6', '7']
nginx_vhosts:
    - {servername: "${domain}", documentroot: "/www/${domain}"}
cert_dir: /var/lib/certs
 
 
vhost_front.tmpl
upstream static_app {
  server ${ ip_addr_back }:80 weight=1;
}
server {
  listen 80;
  server_name {{ item.servername }};
  location / {
    return 301 https://$host$request_uri;
  }
}
server {
  listen 443 ssl;
  root {{ item.documentroot }}/html/;
  index index.htm;
  server_name {{ item.servername }};
  ssl_certificate     /var/lib/certs/{{ item.servername }}/{{ ssl_certificate }};
  ssl_certificate_key /var/lib/certs/{{ item.servername }}/{{ ssl_certificate_key }};
  ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers         HIGH:!aNULL:!MD5;
  location / {
    proxy_pass http://static_app;
  }
}
 
 
ansible.cfg
[defaults]
host_key_checking=false
inventory=./hosts.yml
vault_password_file=./.ansible_vault_pass
 
 
roles\nginx\handlers\main.yml
---
# handlers file for nginx
- name: reloaded nginx
  service:
    name: nginx
    state: reloaded
- name: restarted nginx
  service:
    name: nginx
    state: restarted
 
 
roles\nginx\templates\index.j2
Hello from {{ item.servername }}
Days of the week:
{% for item in days%}
{{ loop.index }}  {{ item|upper }}
{% endfor %}
 
 
roles\nginx\templates\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 {{ sendfile }};
tcp_nopush {{ tcp_nopush }};
tcp_nodelay {{ tcp_nodelay }};
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/*;
}
 
 
roles\nginx\templates\vhost_back.j2
server {
        listen 80 default_server;
        listen [::]:80 default_server;
        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;
        server_name _;
        location / {
                try_files $uri $uri/ =404;
        }
}
 
 
roles\nginx\tasks\main.yml
---
# tasks file for nginx
- name: Copy ssh-keys in home dir
  copy:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
    mode: '0644'
  with_items: "{{ keys }}"
- name: Install web server NGINX
  apt:
    name: nginx
    state: present
    update_cache: true
- name: Enable and ensure is started NGINX service
  service:
    name: nginx
    enabled: true
    state: started
- name: Create dir for certs
  file:
    path: "{{ cert_dir }}/{{ item.servername }}"
    state: directory
    mode: '0644'
  with_items: "{{ nginx_vhosts }}"
- name: Create Domain www dir
  file:
    path: "/www/{{ item.servername }}/html"
    state: directory
    mode: '0644'
  with_items: "{{ nginx_vhosts }}"
 
 
roles\nginx_conf\tasks\main.yml
---
- name: Copy nginx file
  template:
    src: nginx.j2
    dest: /etc/nginx.conf
  notify:
    - reloaded nginx
  when: ansible_hostname == "serv-1"
- name: Copy certs
  copy:
    src: "./{{ ssl_certificate }}"
    dest: "/var/lib/certs/{{ item.servername }}/{{ ssl_certificate }}"
  with_items: "{{ nginx_vhosts }}"
  when: ansible_hostname == "serv-1"
- name: Copy certs key
  copy:
    src: "./{{ ssl_certificate_key }}"
    dest: "/var/lib/certs/{{ item.servername }}/{{ ssl_certificate_key }}"
  with_items: "{{ nginx_vhosts }}"
  when: ansible_hostname == "serv-1"
- name: Create vhost files front
  template:
    src: vhost_front.j2
    dest: "/etc/nginx/sites-available/{{ item.servername }}.conf"
  with_items: "{{ nginx_vhosts }}"
  when: ansible_hostname == "serv-1"
  notify:
    - reloaded nginx
- name: Create symlink vhost on front
  file:
    src: "/etc/nginx/sites-available/{{ item.servername }}.conf"
    dest: "/etc/nginx/sites-enabled/{{ item.servername }}.conf"
    state: link
    force: true
  when: ansible_hostname == "serv-1"
  with_items: "{{ nginx_vhosts }}"
  notify:
    - reloaded nginx
- name: Create vhost files back
  template:
    src: vhost_back.j2
    dest: "/etc/nginx/sites-enabled/default"
  when: ansible_hostname == "serv-2"
  notify:
    - reloaded nginx
- name: Create index.htm files
  template:
    src: index.j2
    dest: "/var/www/html/index.htm"
  with_items: "{{ nginx_vhosts }}"
  when: ansible_hostname == "serv-2"
 
 
playbook.yaml
- hosts:
  - all
  become: true
  roles:
    - role: nginx
      tags:
        - install_nginx
    - role: nginx_conf
      tags:
        - config_nginx
 

Комментарии пользователей

Эту новость ещё не комментировалиНаписать комментарий
Анонимам нельзя оставоять комментарии, зарегистрируйтесь!

Контакты Группа ВК Сборник материалов по Cisco, Asterisk, Windows Server, Python и Django, SQL и T-SQL, FreeBSD и LinuxКод обмена баннерами Видео к IT статьям на YoutubeВидео на другие темы Смотреть
Мои друзья: Советы, помощь, инструменты для сис.админа, статическая и динамическая маршрутизация, FreeBSD

© Snakeproject.ru создан в 2013 году.
При копировании материала с сайта - оставьте ссылку.
Весь материал на сайте носит ознакомительный характер,
за его использование другими людьми, автор ответственности не несет.

Рейтинг@Mail.ru
Рейтинг@Mail.ru Яндекс.Метрика





Поддержать автора и проект