
Работа с AWS SNS и Terraform в Unix/Linux
Amazon Simple Notification Service (SNS) – гибкий, полностью управляемый сервис передачи сообщений по модели «издатель-подписчик» и уведомлений для мобильных устройств, который позволяет координировать доставку сообщений подписанным конечным точкам и клиентам. С помощью SNS можно рассылать сообщения большому количеству подписчиков, включая распределенные системы и сервисы, а также мобильные устройства. Сервис легко настраивается и прост в работе. Он позволяет надежно отправлять уведомления всем конечным точкам при любых масштабах. Начать работу с SNS можно за несколько минут, используя Консоль управления AWS, интерфейс командной строки AWS или AWS SDK всего с тремя простыми API. SNS позволяет забыть про сложности и дополнительные расходы, связанные с обслуживанием выделенного ПО и инфраструктуры для отправки сообщений, а также с управлением таковыми.
Установка 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 SNS и Terraform в Unix/Linux
У меня есть папка terraform, в ней у меня будут лежать провайдеры с которыми я буду работать. Т.к в этом примере я буду использовать AWS, то создам данную папку и перейду в нее. Далее, в этой папке, стоит создать:
$ mkdir examples modules
В папке examples, я буду хранить так званые «плейбуки» для разварачивания различных служб, например — zabbix-server, grafana, web-серверы и так далее. В modules директории, я буду хранить все необходимые модули.
Начнем писать модуль, но для этой задачи, я создам папку:
$ mkdir modules/sns
Переходим в нее:
$ cd modules/sns
Открываем файл:
$ vim sns.tf
В данный файл, вставляем:
#--------------------------------------------------- # Create AWS SNS topic #--------------------------------------------------- resource "aws_sns_topic" "sns_topic" { #name_prefix = "${lower(var.name)}-sns-" name = "${lower(var.name)}-sns-${lower(var.environment)}" display_name = "${lower(var.name)}-sns-${lower(var.environment)}" delivery_policy = "${data.template_file.sns_topic_delivery_policy_document.rendered}" depends_on = ["data.template_file.sns_topic_delivery_policy_document"] } data "template_file" "sns_topic_delivery_policy_document" { template = "${file("${path.module}/policies/sns_topic_delivery_policy_document.json.tpl")}" vars { minDelayTarget = "${var.minDelayTarget}" maxDelayTarget = "${var.maxDelayTarget}" numRetries = "${var.numRetries}" numMaxDelayRetries = "${var.numMaxDelayRetries}" numNoDelayRetries = "${var.numNoDelayRetries}" numMinDelayRetries = "${var.numMinDelayRetries}" backoffFunction = "${var.backoffFunction}" disableSubscriptionOverrides = "${var.disableSubscriptionOverrides}" } } #--------------------------------------------------- # Create AWS SNS topic policies #--------------------------------------------------- resource "aws_sns_topic_policy" "sns_topic_policy" { arn = "${aws_sns_topic.sns_topic.arn}" policy = "${data.aws_iam_policy_document.sns_topic_policy_document.json}" depends_on = ["aws_sns_topic.sns_topic", "data.aws_iam_policy_document.sns_topic_policy_document"] } data "aws_iam_policy_document" "sns_topic_policy_document" { policy_id = "__default_policy_ID" statement { actions = [ "SNS:Subscribe", "SNS:SetTopicAttributes", "SNS:RemovePermission", "SNS:Receive", "SNS:Publish", "SNS:ListSubscriptionsByTopic", "SNS:GetTopicAttributes", "SNS:DeleteTopic", "SNS:AddPermission", ] condition { test = "StringEquals" variable = "AWS:SourceOwner" values = [ "${var.account-id}", ] } effect = "Allow" principals { type = "AWS" identifiers = ["*"] } resources = [ "${aws_sns_topic.sns_topic.arn}", ] sid = "__default_statement_ID" } } #--------------------------------------------------- # Create AWS SNS topic subscription #--------------------------------------------------- resource "aws_sns_topic_subscription" "sns_topic_subscription" { topic_arn = "${aws_sns_topic.sns_topic.id}" confirmation_timeout_in_minutes = "${var.confirmation_timeout_in_minutes}" endpoint_auto_confirms = "${var.endpoint_auto_confirms}" raw_message_delivery = "${var.raw_message_delivery}" protocol = "${var.sns_protocol}" endpoint = "${var.sns_endpoint}" depends_on = ["aws_sns_topic.sns_topic"] }
Открываем файл:
$ vim variables.tf
И прописываем:
#----------------------------------------------------------- # Global or/and default variables #----------------------------------------------------------- variable "name" { description = "Name to be used on all resources as prefix" default = "TEST-SNS" } 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 "account-id" { description = "Account ID" default = "" } variable "delivery_policy" { description = "Delivery policy" default = "" } variable "sns_protocol" { description = "The protocol to use. The possible values for this are: sqs, sms, lambda, application. (http or https are partially supported, see below) (email is option but unsupported, see below)." default = "sqs" } variable "sns_endpoint" { description = "The endpoint to send data to, the contents will vary with the protocol. (see below for more information)" default = "" } variable "confirmation_timeout_in_minutes" { description = "Set timeout in minutes. Integer indicating number of minutes to wait in retying mode for fetching subscription arn before marking it as failure. Only applicable for http and https protocols (default is 1 minute)." default = "1" } variable "endpoint_auto_confirms" { description = "Enable endpoint auto confirms. Boolean indicating whether the end point is capable of auto confirming subscription e.g., PagerDuty (default is false)" default = "false" } variable "raw_message_delivery" { description = "Set raw message delivery.Boolean indicating whether or not to enable raw message delivery (the original message is directly passed, not wrapped in JSON with the original message in the message property) (default is false)." default = "false" } #Delivery policies variable "minDelayTarget" { description = "Set minDelayTarget. Max=20" default = "19" } variable "maxDelayTarget" { description = "Set maxDelayTarget. Max=20" default = "19" } variable "numRetries" { description = "" default = "3" } variable "numMaxDelayRetries" { description = "" default = "0" } variable "numNoDelayRetries" { description = "" default = "0" } variable "numMinDelayRetries" { description = "" default = "0" } variable "backoffFunction" { description = "Set backoffFunction. Can set: arithmetic, exponential or linear." default = "linear" } variable "disableSubscriptionOverrides" { description = "" default = "false" }
Собственно в этом файле храняться все переменные. Спасибо кэп!
Открываем последний файл:
$ vim outputs.tf
И в него вставить нужно следующие строки:
output "sns_topic_id" { value = "${aws_sns_topic.sns_topic.id}" } output "sns_topic_arn" { value = "${aws_sns_topic.sns_topic.arn}" } output "sns_topic_policy_id" { value = "${aws_sns_topic_subscription.sns_topic_subscription.id}" }
Создаем папку для полисей:
$ mkdir policies
Создаем файл с полисями:
$ vim sns_topic_delivery_policy_document.json.tpl
Прописываем:
{ "http": { "defaultHealthyRetryPolicy": { "minDelayTarget": ${minDelayTarget}, "maxDelayTarget": ${maxDelayTarget}, "numRetries": ${numRetries}, "numMaxDelayRetries": ${numMaxDelayRetries}, "numNoDelayRetries": ${numNoDelayRetries}, "numMinDelayRetries": ${numMinDelayRetries}, "backoffFunction": "${backoffFunction}" }, "disableSubscriptionOverrides": ${disableSubscriptionOverrides} } }
Переходим теперь в папку aws/examples и создадим еще одну папку для проверки написанного чуда:
$ mkdir sns && cd $_
Внутри созданной папки открываем файл:
$ vim main.tf
И вставим в него следующий код:
# # MAINTAINER Vitaliy Natarov "vitaliy.natarov@yahoo.com" # terraform { required_version = "> 0.9.0" } provider "aws" { region = "us-east-1" # alias = "us-east-1" shared_credentials_file = "${pathexpand("~/.aws/credentials")}" # access_key = "${var.aws_access_key}" # secret_key = "${var.aws_secret_key}" } module "sns" { source = "../../modules/sns" name = "TEST-SNS" environment = "PROD" # sns_protocol = "sqs" sns_endpoint = "arn:aws:sqs:us-east-1:316963130188:my_sqs" }
Еще полезности:
Работа с 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
Все уже написано и готово к использованию. Ну что, начнем тестирование. В папке с вашим плейбуком, выполняем:
$ 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 SNS и Terraform в Unix/Linux» завершена.