
Работа с AWS elasticache и Terraform в Unix/Linux
Amazon ElastiCache – это веб-сервис, упрощающий развертывание и масштабирование в облаке хранилища или кэша в памяти, а также управление ими. Сервис повышает производительность интернет-приложений, позволяя получать информацию не только из баз данных, размещенных на дисках, но и из управляемых хранилищ данных в памяти, которые работают быстрее и безопаснее. Amazon ElastiCache поддерживает два сервиса с открытым исходным кодом для размещения данных в памяти.
- Redis – быстрое хранилище данных и кэш в памяти с открытым исходным кодом. Amazon ElastiCache для Redis – это совместимый с Redis сервис хранения и кэширования данных в памяти, который обеспечивает простоту использования и функциональность Redis, а также доступность, надежность, масштабируемость и производительность, подходящие для самых требовательных приложений. Доступны как кластеры, состоящие из одного узла, так и кластеры, включающие до 15 сегментов, что обеспечивает масштабируемость до 3,55 ТиБ данных в памяти. Сервис поддерживает изменение размера работающего кластера, что позволяет без простоя масштабировать кластеры Redis в сторону увеличения или в сторону уменьшения и адаптироваться к изменяющемуся спросу. Сервис соответствует требованиям HIPAA и предлагает шифрование данных при передаче и хранении, а также Redis AUTH для безопасной передачи данных между узлами и надежного хранения конфиденциальных данных, таких как персональная информация (PII). ElastiCache для Redis – это полностью управляемый, масштабируемый и безопасный сервис. Он идеально подходит для высокопроизводительных примеров использования, таких как мобильные и интернет-приложения, приложения, используемые в здравоохранении и финансовой сфере, игры, рекламные технологии и «Интернет вещей».
- Memcached – широко распространенная система кэширования объектов в памяти. Используемые в ElastiCache протоколы полностью совместимы с Memcached, поэтому все популярные инструменты, уже используемые в существующих средах Memcached, будут эффективно работать с этим сервисом.
Amazon ElastiCache автоматически определяет и заменяет вышедшие из строя узлы, снижая издержки, связанные с самоуправляемыми инфраструктурами, и формирует отказоустойчивую систему, которая сводит к минимуму риск перегрузок баз данных и его негативное влияние на время загрузки веб-сайтов и приложений. Благодаря интеграции с Amazon CloudWatch сервис Amazon ElastiCache предлагает расширенные возможности мониторинга ключевых показателей производительности, связанных с узлами Redis или Memcached.
С помощью Amazon ElastiCache вы сможете добавить уровень данных в памяти в свою инфраструктуру за считанные минуты, используя Консоль управления AWS.
Установка terraform в Unix/Linux
Установка крайне примитивная и я описал как это можно сделать тут:
Установка terraform в Unix/Linux
Так же, в данной статье, я создал скрипт для автоматической установки данного ПО. Он был протестирован на CentOS 6/7, Debian 8 и на Mac OS X. Все работает должным образом!
Чтобы получить помощь по использованию команд, выполните:
$ terraform Usage: terraform [--version] [--help] <command> [args] The available commands for execution are listed below. The most common, useful commands are shown first, followed by less common or more advanced commands. If you're just getting started with Terraform, stick with the common commands. For the other commands, please read the help and docs before usage. Common commands: apply Builds or changes infrastructure console Interactive console for Terraform interpolations destroy Destroy Terraform-managed infrastructure env Workspace management fmt Rewrites config files to canonical format get Download and install modules for the configuration graph Create a visual graph of Terraform resources import Import existing infrastructure into Terraform init Initialize a Terraform working directory output Read an output from a state file plan Generate and show an execution plan providers Prints a tree of the providers used in the configuration push Upload this Terraform module to Atlas to run refresh Update local state file against real resources show Inspect Terraform state or plan taint Manually mark a resource for recreation untaint Manually unmark a resource as tainted validate Validates the Terraform files version Prints the Terraform version workspace Workspace management All other commands: debug Debug output management (experimental) force-unlock Manually unlock the terraform state state Advanced state management
Приступим к использованию!
Работа с AWS elasticache и Terraform в Unix/Linux
У меня есть папка terraform, в ней у меня будут лежать провайдеры с которыми я буду работать. Т.к в этом примере я буду использовать AWS, то создам данную папку и перейду в нее. Далее, в этой папке, стоит создать:
$ mkdir examples modules
В папке examples, я буду хранить так званые «плейбуки» для разварачивания различных служб, например — zabbix-server, grafana, web-серверы и так далее. В modules директории, я буду хранить все необходимые модули.
Начнем писать модуль, но для этой задачи, я создам папку:
$ mkdir modules/elasticache
Переходим в нее:
$ cd modules/elasticache
Открываем файл:
$ vim elasticache.tf
В данный файл, вставляем:
#--------------------------------------------------- # Create AWS elasticache security group (SG) #--------------------------------------------------- resource "aws_elasticache_security_group" "elasticache_sg" { # NOTE: ElastiCache Subnet Groups are only for use when working with an ElastiCache cluster inside of a VPC. If you are on EC2 Classic, see the ElastiCache Security Group resource. # NOTE: ElastiCache Security Groups are for use only when working with an ElastiCache cluster outside of a VPC. If you are using a VPC, see the ElastiCache Subnet Group resource. count = "${length(var.security_group_names) !=0 && length(var.subnet_ids) ==0 ? 1 : 0}" name = "${lower(var.name)}-${var.engine}-sg-${lower(var.environment)}" description = "Elasticache security group (SG) which managed by ${var.orchestration}" security_group_names = ["${var.security_group_names}"] } #--------------------------------------------------- # Create AWS elasticache subnet group #--------------------------------------------------- resource "aws_elasticache_subnet_group" "elasticache_subnet_group" { # NOTE: ElastiCache Subnet Groups are only for use when working with an ElastiCache cluster inside of a VPC. If you are on EC2 Classic, see the ElastiCache Security Group resource. # NOTE: ElastiCache Security Groups are for use only when working with an ElastiCache cluster outside of a VPC. If you are using a VPC, see the ElastiCache Subnet Group resource. count = "${length(var.subnet_ids) !=0 && length(var.security_group_names) ==0 ? 1 : 0}" name = "${lower(var.name)}-${var.engine}-subnet-group-${lower(var.environment)}" description = "Elasticache subnet group which managed by ${var.orchestration}" subnet_ids = ["${var.subnet_ids}"] } #--------------------------------------------------- # Create AWS elasticache parameter group #--------------------------------------------------- resource "aws_elasticache_parameter_group" "elasticache_parameter_group" { count = "${length(var.parameters_for_parameter_group) !=0 && var.create_custom_elasticache_parameter_group ? 1 : 0}" name = "${lower(var.name)}-${var.engine}-parameter-group-${lower(var.environment)}" description = "Elasticache parameter group which managed by ${var.orchestration}" family = "${var.elasticache_parameter_group_family[var.engine]}" parameter = ["${var.parameters_for_parameter_group}"] } #--------------------------------------------------- # Create AWS elasticache cluster #--------------------------------------------------- resource "aws_elasticache_cluster" "elasticache_cluster" { count = "${var.num_cache_nodes ==1 && var.number_cluster_replicas ==0 && var.create_single_cluster ? 1 : 0}" cluster_id = "${lower(var.name)}-${lower(var.engine)}-${lower(var.environment)}" engine = "${var.engine}" node_type = "${var.node_type}" port = "${var.default_ports[var.engine]}" num_cache_nodes = "${var.num_cache_nodes}" subnet_group_name = "${var.subnet_group_name}" security_group_names = ["${var.security_group_names_for_cluster}"] security_group_ids = ["${var.security_group_ids}"] parameter_group_name = "${var.parameter_group_name[var.engine] !="" ? var.parameter_group_name[var.engine] : aws_elasticache_parameter_group.elasticache_parameter_group.name}" maintenance_window = "${var.maintenance_window}" snapshot_window = "${var.snapshot_window}" #snapshot_retention_limit = "${var.snapshot_retention_limit }" availability_zone = "${var.availability_zone}" notification_topic_arn = "${var.notification_topic_arn}" tags { Name = "${lower(var.name)}-${var.engine}-cluster-${lower(var.environment)}" Environment = "${var.environment}" Orchestration = "${var.orchestration}" Createdby = "${var.createdby}" } } #--------------------------------------------------- # Create AWS elasticache replication group #--------------------------------------------------- resource "aws_elasticache_replication_group" "elasticache_replication_group" { # Redis Master with One Replica with 1 shard count = "${var.num_cache_nodes >1 && var.number_cluster_replicas ==1 && var.create_single_cluster !="true" ? 1 : 0}" replication_group_id = "${lower(var.name)}-${lower(var.engine)}-${lower(var.environment)}" replication_group_description = "The ${var.engine} master with 1 replica shard which managed by ${var.orchestration}" node_type = "${var.node_type}" number_cache_clusters = "${var.num_cache_nodes}" port = "${var.default_ports[var.engine]}" engine = "${var.engine}" engine_version = "${var.engine_version}" availability_zones = ["us-east-1a", "us-east-1c"] automatic_failover_enabled = "${var.automatic_failover_enabled}" subnet_group_name = "${var.subnet_group_name}" security_group_names = ["${var.security_group_names_for_cluster}"] security_group_ids = ["${var.security_group_ids}"] parameter_group_name = "${var.parameter_group_name[var.engine] !="" ? var.parameter_group_name[var.engine] : aws_elasticache_parameter_group.elasticache_parameter_group.name}" at_rest_encryption_enabled = "${var.at_rest_encryption_enabled}" transit_encryption_enabled = "${var.transit_encryption_enabled}" #auth_token = "${var.auth_token}" auto_minor_version_upgrade = "${var.auto_minor_version_upgrade}" snapshot_name = "${var.snapshot_name}" maintenance_window = "${var.maintenance_window}" snapshot_window = "${var.snapshot_window}" snapshot_retention_limit = "${var.snapshot_retention_limit}" apply_immediately = "${var.apply_immediately}" notification_topic_arn = "${var.notification_topic_arn}" tags { Name = "${lower(var.name)}-${var.engine}-cluster-${lower(var.environment)}" Environment = "${var.environment}" Orchestration = "${var.orchestration}" Createdby = "${var.createdby}" } } resource "aws_elasticache_replication_group" "elasticache_replication_group_2" { # Redis Master with One Replica for each nodes count = "${var.num_cache_nodes >1 && var.number_cluster_replicas ==2 && var.create_single_cluster !="true" ? 1 : 0}" replication_group_id = "${lower(var.name)}-${lower(var.engine)}-${lower(var.environment)}" replication_group_description = "The ${var.engine} master with 2 replica shards which managed by ${var.orchestration}" node_type = "${var.node_type}" port = "${var.default_ports[var.engine]}" engine = "${var.engine}" engine_version = "${var.engine_version}" automatic_failover_enabled = "${var.automatic_failover_enabled}" subnet_group_name = "${var.subnet_group_name}" security_group_names = ["${var.security_group_names_for_cluster}"] security_group_ids = ["${var.security_group_ids}"] parameter_group_name = "${var.parameter_group_name[var.engine] !="" ? var.parameter_group_name[var.engine] : aws_elasticache_parameter_group.elasticache_parameter_group.name}" at_rest_encryption_enabled = "${var.at_rest_encryption_enabled}" transit_encryption_enabled = "${var.transit_encryption_enabled}" #auth_token = "${var.auth_token}" auto_minor_version_upgrade = "${var.auto_minor_version_upgrade}" snapshot_name = "${var.snapshot_name}" maintenance_window = "${var.maintenance_window}" snapshot_window = "${var.snapshot_window}" snapshot_retention_limit = "${var.snapshot_retention_limit}" apply_immediately = "${var.apply_immediately}" notification_topic_arn = "${var.notification_topic_arn}" cluster_mode { replicas_per_node_group = "${var.cluster_mode_replicas_per_node_group}" num_node_groups = "${var.num_cache_nodes}" } lifecycle { create_before_destroy = true, } tags { Name = "${lower(var.name)}-${var.engine}-cluster-${lower(var.environment)}" Environment = "${var.environment}" Orchestration = "${var.orchestration}" Createdby = "${var.createdby}" } }
Открываем файл:
$ vim variables.tf
И прописываем:
#----------------------------------------------------------- # Global or/and default variables #----------------------------------------------------------- variable "name" { description = "Name to be used on all resources as prefix" default = "TEST-elasticache" } variable "region" { description = "The region where to deploy this code (e.g. us-east-1)." default = "us-east-1" } variable "environment" { description = "Environment for service" default = "STAGE" } variable "orchestration" { description = "Type of orchestration" default = "Terraform" } variable "createdby" { description = "Created by" default = "Vitaliy Natarov" } variable "security_group_names" { description = "List of EC2 security group names to be authorized for ingress to the cache security group" type = "list" default = [] } variable "subnet_ids" { description = "List of VPC Subnet IDs for the cache subnet group" type = "list" default = [] } variable "parameters_for_parameter_group" { description = "List of parameters for custom elasticache parameter group" type = "list" default = [] } variable "create_custom_elasticache_parameter_group" { description = "If true, will create elasticache parameter group" default = "true" } variable "engine" { description = "Name of the cache engine to be used for this cache cluster. Valid values for this parameter are memcached or redis" default = "redis" } variable "engine_version" { description = "The version number of the cache engine to be used for the cache clusters in this replication group." default = "" } variable "default_ports" { description = "Default database ports" type = "map" default = { redis = "6379" memcached = "11211" } } variable "elasticache_parameter_group_family" { description = "Set DB group family" type = "map" default = { redis = "redis3.2" memcached = "memcached1.4" } } variable "create_single_cluster" { description = "Enable to create a cluster without any replicas. Default - true" default = "true" } variable "node_type" { description = "The cluster node type. Ex: cache.t2.micro" default = "cache.t2.micro" } variable "num_cache_nodes" { description = "The number of cache nodes that the cache cluster has. Cannot create a Redis cluster with a NumCacheNodes parameter greater than 1." default = "1" } variable "parameter_group_name" { description = "Name of the parameter group associated with this cache cluster. Ex: default.redis3.2, default.memcached1.4 etc" type = "map" default = { redis = "" memcached = "" } } variable "subnet_group_name" { description = "Name of the subnet group associated to the cache cluster." default = "" } variable "security_group_names_for_cluster" { description = "List of security group names associated with this cache cluster." type = "list" default = [] } variable "security_group_ids" { description = "List VPC security groups associated with the cache cluster." type = "list" default = [] } variable "maintenance_window" { description = "Specifies the weekly time range for when maintenance on the cache cluster is performed. The format is ddd:hh24:mi-ddd:hh24:mi (24H Clock UTC). The minimum maintenance window is a 60 minute period. Example: sun:05:00-sun:09:00" default = "sun:05:00-sun:09:00" } variable "snapshot_window" { description = "The daily time range (in UTC) during which ElastiCache will begin taking a daily snapshot of the cache cluster. Format: hh24:mi-hh24:mi. The minimum snapshot window is a 60 minute period. Example: 05:00-09:00" default = "01:00-05:00" } variable "availability_zone" { description = "The Availability Zone for the cache cluster." default = "" } variable "notification_topic_arn" { description = "An Amazon Resource Name (ARN) of an SNS topic that ElastiCache notifications get sent to." default = "" } variable "snapshot_retention_limit" { description = "The number of days for which ElastiCache will retain automatic cache cluster snapshots before deleting them. For example, if you set SnapshotRetentionLimit to 5, then a snapshot that was taken today will be retained for 5 days before being deleted. If the value of SnapshotRetentionLimit is set to zero (0), backups are turned off. Please note that setting a snapshot_retention_limit is not supported on cache.t1.micro or cache.t2.* cache nodes" default = "7" } variable "replication_group_id" { description = "The replication group to which this cache cluster belongs." default = "replication-cluster-group" } variable "number_cluster_replicas" { description = "Number of cluster replicas which will create" default = "0" } variable "automatic_failover_enabled" { description = "Specifies whether a read-only replica will be automatically promoted to read/write primary if the existing primary fails. Defaults to false." default = "true" } variable "auto_minor_version_upgrade" { description = "Specifies whether a minor engine upgrades will be applied automatically to the underlying Cache Cluster instances during the maintenance window. Defaults to true." default = "true" } variable "at_rest_encryption_enabled" { description = "Whether to enable encryption at rest." default = "false" } variable "transit_encryption_enabled" { description = "Whether to enable encryption in transit." default = "false" } variable "auth_token" { description = "The password used to access a password protected server. Can be specified only if transit_encryption_enabled = true." default = "AUTHtoken666AUTHtoken666AUTHtoken666AUTHtoken666" } variable "snapshot_name" { description = "The name of a snapshot from which to restore data into the new node group. Changing the snapshot_name forces a new resource." default = "" } variable "apply_immediately" { description = "Specifies whether any modifications are applied immediately, or during the next maintenance window. Default is false." default = "false" } variable "cluster_mode_replicas_per_node_group" { description = "Specify the number of replica nodes in each node group. Valid values are 0 to 5. Changing this number will force a new resource." default = "1" }
Собственно в этом файле храняться все переменные. Спасибо кэп!
Открываем последний файл:
$ vim outputs.tf
И в него вставить нужно следующие строки:
output "elasticache_sg_ids" { description = "" value = "${aws_elasticache_security_group.elasticache_sg.*.id}" } output "elasticache_subnet_group" { description = "" value = "${aws_elasticache_subnet_group.elasticache_subnet_group.*.id}" } output "elasticache_parameter_group_names" { description = "" value = "${aws_elasticache_parameter_group.elasticache_parameter_group.*.name}" } output "elasticache_cluster_ids" { description = "" value = "${aws_elasticache_cluster.elasticache_cluster.*.id}" } output "elasticache_replication_group_ids" { description = "" value = "${aws_elasticache_replication_group.elasticache_replication_group.*.id}" } output "elasticache_replication_group_2_ids" { description = "" value = "${aws_elasticache_replication_group.elasticache_replication_group_2.*.id}" }
Переходим теперь в папку aws/examples и создадим еще одну папку для проверки написанного чуда:
$ mkdir elasticache && cd $_
Внутри созданной папки открываем файл:
$ vim main.tf
И вставим в него следующий код:
# # MAINTAINER Vitaliy Natarov "vitaliy.natarov@yahoo.com" # terraform { required_version = "> 0.9.0" } provider "aws" { region = "us-east-1" shared_credentials_file = "${pathexpand("~/.aws/credentials")}" profile = "default" } module "vpc" { source = "../../modules/vpc" name = "TEST-VPC" environment = "PROD" # VPC instance_tenancy = "default" enable_dns_support = "true" enable_dns_hostnames = "true" assign_generated_ipv6_cidr_block = "false" enable_classiclink = "false" vpc_cidr = "172.31.0.0/16" private_subnet_cidrs = ["172.31.64.0/20"] public_subnet_cidrs = ["172.31.80.0/20"] availability_zones = ["us-east-1a", "us-east-1b"] allowed_ports = ["6379", "11211"] allow_cidrs_for_allowed_ports = [{ "6379" = ["0.0.0.0/0"] "11211" = ["0.0.0.0/0"] }] #Internet-GateWay enable_internet_gateway = "true" #NAT enable_nat_gateway = "false" single_nat_gateway = "true" #VPN enable_vpn_gateway = "false" #DHCP enable_dhcp_options = "false" # EIP enable_eip = "false" } module "elasticache" { source = "../../modules/elasticache" name = "TEST" region = "us-east-1" environment = "PROD" # NOTE: ElastiCache Subnet Groups are only for use when working with an ElastiCache cluster inside of a VPC. If you are on EC2 Classic, see the ElastiCache Security Group resource. # NOTE: ElastiCache Security Groups are for use only when working with an ElastiCache cluster outside of a VPC. If you are using a VPC, see the ElastiCache Subnet Group resource. # I HAVE GOT ISSUE WHEN USED "ElastiCache Security Groups". SO I PREFERED ElastiCache Subnet Groups #aws_elasticache_security_group.elasticache_sg: Error creating CacheSecurityGroup: InvalidParameterValue: Use of cache security groups is not permitted in this API version for your account. security_group_names = [] subnet_ids = ["${module.vpc.vpc-privatesubnet-ids}", "${module.vpc.vpc-publicsubnet-ids}"] create_custom_elasticache_parameter_group = true parameters_for_parameter_group = [ { name = "activerehashing" value = "yes" }, { name = "min-slaves-to-write" value = "2" }, ] engine = "redis" #"memcached" # Not single cluster #create_single_cluster = false #num_cache_nodes = 2 #number_cluster_replicas = 1 #node_type = "cache.m3.medium" # cluster with 2 nodes and 2 shards create_single_cluster = false number_cluster_replicas = 2 num_cache_nodes = 2 node_type = "cache.m3.medium" parameter_group_name = [{ redis = "default.redis3.2.cluster.on" }] }
Еще полезности:
Работа с AWS IAM и Terraform в Unix/Linux
Работа с AWS VPC и Terraform в Unix/Linux
Работа с AWS S3 и Terraform в Unix/Linux
Работа с AWS EC2 и Terraform в Unix/Linux
Работа с AWS ASG(auto scaling group) и Terraform в Unix/Linux
Работа с AWS ELB и Terraform в Unix/Linux
Работа с AWS Route53 и Terraform в Unix/Linux
Работа с AWS RDS и Terraform в Unix/Linux
Работа с AWS SNS и Terraform в Unix/Linux
Работа с AWS SQS и Terraform в Unix/Linux
Работа с AWS KMS и Terraform в Unix/Linux
Работа с AWS NLB и Terraform в Unix/Linux
Работа с AWS CloudWatch и Terraform в Unix/Linux
Работа с AWS ALB и Terraform в Unix/Linux
Работа с AWS MQ broker и Terraform в Unix/Linux
Работа с AWS EFS и Terraform в Unix/Linux
Все уже написано и готово к использованию. Ну что, начнем тестирование. В папке с вашим плейбуком, выполняем:
$ terraform init
Этим действием я инициализирую проект. Затем, подтягиваю модуль:
$ terraform get
PS: Для обновление изменений в самом модуле, можно выполнять:
$ terraform get -update
Проверим валидацию:
$ terraform validate
Запускем прогон:
$ terraform plan
Мне вывело что все у меня хорошо и можно запускать деплой:
$ terraform apply
Как видно с вывода, — все прошло гладко! Чтобы удалить созданное творение, можно выполнить:
$ terraform destroy
Весь материал аплоаджу в github аккаунт для удобства использования:
$ git clone https://github.com/SebastianUA/terraform.git
Вот и все на этом. Данная статья «Работа с AWS elasticache и Terraform в Unix/Linux» завершена.