
Работа с Google Cloud Platform (compute firewall) и Terraform в Unix/Linux
Google Cloud Platrorm — это платформа вида «инфраструктура как сервис» (IaaS), позволяющая клиентам создавать, тестировать и развертывать собственные приложения на инфраструктуре Google, в высокопроизводительных виртуальных машинах.
Google Compute Engine предоставляет виртуальные машины, работающие в инновационных центрах обработки данных Google и всемирной сети.
compute firewall — собственно, — набор правил для обеспечения защиты compute экземпляров. Все что не разрешено, — будет закрыто. Неплохой придумали солюшен для клауда.
Установка terraform в Unix/Linux
Установка крайне примитивная и я описал как это можно сделать тут:
Установка terraform в Unix/Linux
Вот еще полезные статьи по GCP + Terrafrom:
Работа с Google Cloud Platform (compute instance) и Terraform в Unix/Linux
Работа с Google Cloud Platform (compute health check) и Terraform в Unix/Linux
Работа с Google Cloud Platform (compute target pool) и Terraform в Unix/Linux
Работа с Google Cloud Platform (compute forwarding rule) и Terraform в Unix/Linux
Так же, в данной статье, я создал скрипт для автоматической установки данного ПО. Он был протестирован на CentOS 6/7, Debian 8 и на Mac OS X. Все работает должным образом!
Чтобы получить помощь по использованию команд, выполните:
$ terraform --help 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
Приступим к использованию!
Работа с Google Cloud Platform (compute firewall) и Terraform в Unix/Linux
Первое что нужно сделать — это настроить «Cloud Identity». С помощью сервиса Google Cloud Identity вы сможете предоставлять доменам, пользователям и аккаунтам в организации доступ к ресурсам Cloud, а также централизованно управлять пользователями и группами через консоль администратора Google.
Полезное чтиво:
Установка Google Cloud SDK/gcloud в Unix/Linux
У меня есть папка terraform, в ней у меня будут лежать провайдеры с которыми я буду работать. Т.к в этом примере я буду использовать google_cloud_platform, то создам данную папку и перейду в нее. Далее, в этой папке, стоит создать:
$ mkdir examples modules
В папке examples, я буду хранить так званые «плейбуки» для разварачивания различных служб, например — zabbix-server, grafana, web-серверы и так далее. В modules директории, я буду хранить все необходимые модули.
Начнем писать модуль, но для этой задачи, я создам папку:
$ mkdir modules/compute_firewall
Переходим в нее:
$ cd modules/compute_firewall
Открываем файл:
$ vim compute_firewall.tf
В данный файл, вставляем:
#--------------------------------------------------- # Create compute firewall for INGRESS #--------------------------------------------------- resource "google_compute_firewall" "compute_firewall_all_ingress" { count = "${var.enable_all_ingress && upper(var.direction) == "INGRESS" ? 1 : 0}" name = "${lower(var.name)}-fw-${lower(var.environment)}-${lower(var.direction)}" description = "${var.description}" project = "${var.project}" network = "${var.network}" priority = "${var.priority}" source_ranges = "${var.source_ranges}" source_tags = ["${var.source_tags}"] target_tags = ["${var.target_tags}"] direction = "${var.direction}" #destination_ranges = ["${var.destination_ranges}"] #source_service_accounts = ["${var.source_service_accounts}"] #target_service_accounts = ["${var.target_service_accounts}"] allow { protocol = "all" } } resource "google_compute_firewall" "compute_firewall_needed_ingress" { count = "${!var.enable_all_ingress && upper(var.direction) == "INGRESS" && var.allow_protocol !="" && length(var.allow_ports) > 0 ? 1 : 0}" name = "${lower(var.name)}-fw-${lower(var.environment)}-${lower(var.direction)}" description = "${var.description}" project = "${var.project}" network = "${var.network}" priority = "${var.priority}" source_ranges = "${var.source_ranges}" source_tags = ["${var.source_tags}"] target_tags = ["${var.target_tags}"] direction = "${var.direction}" #destination_ranges = ["${var.destination_ranges}"] #source_service_accounts = ["${var.source_service_accounts}"] #target_service_accounts = ["${var.target_service_accounts}"] allow { protocol = "${var.allow_protocol}" ports = ["${var.allow_ports}"] } } #--------------------------------------------------- # Create compute firewall for EGRESS. #--------------------------------------------------- resource "google_compute_firewall" "compute_firewall_all_egress" { count = "${var.enable_all_egress ? 1 : 0}" name = "${lower(var.name)}-fw-${lower(var.environment)}-egress" description = "${var.description}" project = "${var.project}" network = "${var.network}" priority = "${var.priority}" #target_tags = ["${var.target_tags}"] direction = "EGRESS" destination_ranges = ["${var.destination_ranges}"] source_service_accounts = ["${var.source_service_accounts}"] target_service_accounts = ["${var.target_service_accounts}"] allow { protocol = "all" } } resource "google_compute_firewall" "compute_firewall_needed_egress" { count = "${!var.enable_all_egress ? 1 : 0}" name = "${lower(var.name)}-fw-${lower(var.environment)}-egress" description = "${var.description}" project = "${var.project}" network = "${var.network}" priority = "${var.priority}" #target_tags = ["${var.target_tags}"] direction = "EGRESS" destination_ranges = ["${var.destination_ranges}"] source_service_accounts = ["${var.source_service_accounts}"] target_service_accounts = ["${var.target_service_accounts}"] allow { protocol = "${var.allow_protocol}" ports = ["${var.allow_ports}"] } }
Открываем файл:
$ vim variables.tf
И прописываем:
variable "name" { description = "A unique name for the resource, required by GCE. Changing this forces a new resource to be created." default = "TEST" } variable "environment" { description = "Environment for service" default = "STAGE" } variable "project" { description = "The project in which the resource belongs. If it is not provided, the provider project is used." default = "" } variable "network" { description = "The name or self_link of the network to attach this firewall to." default = "default" } variable "description" { description = "Textual description field." default = "" } variable "priority" { description = "The priority for this firewall. Ranges from 0-65535, inclusive. Defaults to 1000. Firewall resources with lower priority values have higher precedence (e.g. a firewall resource with a priority value of 0 takes effect over all other firewall rules with a non-zero priority)." default = "1000" } variable "source_ranges" { description = "A list of source CIDR ranges that this firewall applies to. Can't be used for EGRESS." default = [] } variable "source_tags" { description = "A list of source tags for this firewall. Can't be used for EGRESS." default = [] } variable "target_tags" { description = "A list of target tags for this firewall." default = [] } variable "direction" { description = "Direction of traffic to which this firewall applies; One of INGRESS or EGRESS. Defaults to INGRESS." default = "INGRESS" } variable "destination_ranges" { description = "A list of destination CIDR ranges that this firewall applies to. Can't be used for INGRESS." default = [] } variable "source_service_accounts" { description = "A list of service accounts such that the firewall will apply only to traffic originating from an instance with a service account in this list. Note that as of May 2018, this list can contain only one item, due to a change in the way that these firewall rules are handled. Source service accounts cannot be used to control traffic to an instance's external IP address because service accounts are associated with an instance, not an IP address. source_ranges can be set at the same time as source_service_accounts. If both are set, the firewall will apply to traffic that has source IP address within source_ranges OR the source IP belongs to an instance with service account listed in source_service_accounts. The connection does not need to match both properties for the firewall to apply. source_service_accounts cannot be used at the same time as source_tags or target_tags." default = [] } variable "target_service_accounts" { description = "A list of service accounts indicating sets of instances located in the network that may make network connections as specified in allow. target_service_accounts cannot be used at the same time as source_tags or target_tags. If neither target_service_accounts nor target_tags are specified, the firewall rule applies to all instances on the specified network. Note that as of May 2018, this list can contain only one item, due to a change in the way that these firewall rules are handled." default = [] } variable "allow_protocol" { description = "The name of the protocol to allow. This value can either be one of the following well known protocol strings (tcp, udp, icmp, esp, ah, sctp), or the IP protocol number, or all." default = "" } variable "allow_ports" { description = "List of ports and/or port ranges to allow. This can only be specified if the protocol is TCP or UDP." default = [] } variable "deny_protocol" { description = "The name of the protocol to deny. This value can either be one of the following well known protocol strings (tcp, udp, icmp, esp, ah, sctp), or the IP protocol number, or all." default = "" } variable "deny_ports" { description = "List of ports and/or port ranges to allow. This can only be specified if the protocol is TCP or UDP." default = [] } variable "enable_all_ingress" { description = "Enable all ports for ingress traffic" default = false } variable "enable_all_egress" { description = "Enable all ports for egress traffic" default = true }
Собственно в этом файле храняться все переменные. Спасибо кэп!
Открываем последний файл:
$ vim outputs.tf
И в него вставить нужно следующие строки:
output "all_ingress_firewall_name" { description = "Name of google compute firewall" value = "${google_compute_firewall.compute_firewall_all_ingress.*.name}" } output "all_ingress_firewall_self_link" { description = "Self link" value = "${google_compute_firewall.compute_firewall_all_ingress.*.self_link}" } output "needed_ingress_firewall_name" { description = "Name of google compute firewall" value = "${google_compute_firewall.compute_firewall_needed_ingress.*.name}" } output "needed_ingress_firewall_self_link" { description = "Self link" value = "${google_compute_firewall.compute_firewall_needed_ingress.*.self_link}" } output "all_egress_firewall_name" { description = "Name of google compute firewall" value = "${google_compute_firewall.compute_firewall_all_egress.*.name}" } output "all_egress_firewall_self_link" { description = "Self link" value = "${google_compute_firewall.compute_firewall_all_egress.*.self_link}" } output "needed_egress_firewall_name" { description = "Name of google compute firewall" value = "${google_compute_firewall.compute_firewall_needed_egress.*.name}" } output "needed_egress_firewall_self_link" { description = "Self link" value = "${google_compute_firewall.compute_firewall_needed_egress.*.self_link}" }
Переходим теперь в папку google_cloud_platform/examples и создадим еще одну папку для проверки написанного чуда:
$ mkdir compute_firewall && cd $_
Внутри созданной папки открываем файл:
$ vim main.tf
Вставляем:
# # MAINTAINER Vitaliy Natarov "vitaliy.natarov@yahoo.com" # terraform { required_version = "> 0.9.0" } provider "google" { credentials = "${file("/Users/captain/.config/gcloud/creds/terraform_creds.json")}" project = "terraform-2018" region = "us-east1" } module "compute_firewall" { source = "../../modules/compute_firewall" name = "TEST" project = "terraform-2018" enable_all_ingress = true enable_all_egress = true #enable_all_ingress = false #allow_protocol = "icmp" #allow_ports = ["80", "443"] }
Все уже написано и готово к использованию. Ну что, начнем тестирование. В папке с вашим плейбуком, выполняем:
$ 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
Чтобы поглядеть какие рулы фаервола есть, заюзайте:
$ gcloud alpha compute firewall-rules list
Вот и все на этом. Не уверен что это полный солюшен, но для моего примера и моей таски пойдет. По возможности, добавлю новые рулы.
Данная статья «Работа с Google Cloud Platform (compute firewall) и Terraform в Unix/Linux» завершена.