Рубрики
Uncategorized

Терраформа Часть II

Общие сведения о Terraform Part II, создании нескольких инстансов ec2 и эластичном IP-адресе

Автор оригинала: Bolatito Kabir.

Развертывание нескольких различных экземпляров и подключение elasticIP- Создадим еще один экземпляр в другой зоне доступности и присоединим эластичную области. … Мы будем использовать синтаксис is count. ПОЛЕ. Например, ${count.index} будет интерполировать текущий индекс в … …

variable "avaialability_zones" {
  description = "Run the EC2 Instances in these Availability Zones"
  type = "list"
  default = ["us-east-1c", "us-east-1b", "us-east-1a"]
}

или заставить Terraform получить всю зону доступности от облачного провайдера (мы используем aws) с помощью источника данных (источники данных позволяют получать данные от поставщика, … Он не создает новые ресурсы, а вместо этого извлекает динамические данные из облака … Обновление ... данные «aws_availability_zones» «все» {} Так как мы решили использовать нашу пользовательскую зону доступности. ...

resource "aws_instance" "server" {
  count = 2
  ami = "ami-2d39803a"
  instance_type = "t2.micro"
  availability_zone = "${element(var.avaialability_zones, count.index)}"
  tags {
      Name = "server-${count.index}"
      Environment = "Production ${count.index}"
      App = "ecommerce"
  }
}

Объяснение вышесказанного в псевдокоде.

##This is just pseudo code. It won't actually work in Terraform. 
# Create two ec2 instances
count = 2
for i = 0; i < count; i++ {
  resource "aws_instance" "server" {
    ami = "ami-2d39803a"
    instance_type = "t2.micro" 
    ## set them into different availability zone
    availability_zone = "${avaialability_zones[i]}" 
    ## number each instances created
    tags {
      Name = "server-${i}"
      Environment = "Production ${i}"
      App = "ecommerce"
    }
  }  
}

Тест

$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
aws_instance.server[0]: Refreshing state... (ID: i-052a34a0680983ae0)
------------------------------------------------------------------------
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create
  ~ update in-place
Terraform will perform the following actions:
~ aws_instance.server[0]
      tags.Environment:             "Production" => "Production 0"
      tags.Name:                    "server-one" => "server-0"
+ aws_instance.server[1]
      id:                           
      ami:                          "ami-2d39803a"
      arn:                          
      associate_public_ip_address:  
      availability_zone:            "us-east-1b"
      cpu_core_count:               
      cpu_threads_per_core:         
      ebs_block_device.#:           
      ephemeral_block_device.#:     
      get_password_data:            "false"
      host_id:                      
      instance_state:               
      instance_type:                "t2.micro"
      ipv6_address_count:           
      ipv6_addresses.#:             
      key_name:                     
      network_interface.#:          
      network_interface_id:         
      password_data:                
      placement_group:              
      primary_network_interface_id: 
      private_dns:                  
      private_ip:                   
      public_dns:                   
      public_ip:                    
      root_block_device.#:          
      security_groups.#:            
      source_dest_check:            "true"
      subnet_id:                    
      tags.%:                       "3"
      tags.App:                     "ecommerce"
      tags.Environment:             "Production 1"
      tags.Name:                    "server-1"
      tenancy:                      
      volume_tags.%:                
      vpc_security_group_ids.#:     
Plan: 1 to add, 1 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

Мы видим, что начальный экземпляр ec2 мы раскручили ~ aws_instance.сервер[0] будет изменен, и другой экземпляр + aws_instance.сервер[1] будет добавлено с другим именем тега, именем среды и обоими в … …

$ terraform apply -auto-approve
aws_instance.server[0]: Refreshing state... (ID: i-052a34a0680983ae0)
aws_instance.server[0]: Modifying... (ID: i-052a34a0680983ae0)
  tags.Environment: "Production" => "Production 0"
  tags.Name:        "server-one" => "server-0"
aws_instance.server[1]: Creating...
  ami:                          "" => "ami-2d39803a"
  arn:                          "" => ""
  associate_public_ip_address:  "" => ""
  availability_zone:            "" => "us-east-1b"
  cpu_core_count:               "" => ""
  cpu_threads_per_core:         "" => ""
  ebs_block_device.#:           "" => ""
  ephemeral_block_device.#:     "" => ""
  get_password_data:            "" => "false"
  host_id:                      "" => ""
  instance_state:               "" => ""
  instance_type:                "" => "t2.micro"
  ipv6_address_count:           "" => ""
  ipv6_addresses.#:             "" => ""
  key_name:                     "" => ""
  network_interface.#:          "" => ""
  network_interface_id:         "" => ""
  password_data:                "" => ""
  placement_group:              "" => ""
  primary_network_interface_id: "" => ""
  private_dns:                  "" => ""
  private_ip:                   "" => ""
  public_dns:                   "" => ""
  public_ip:                    "" => ""
  root_block_device.#:          "" => ""
  security_groups.#:            "" => ""
  source_dest_check:            "" => "true"
  subnet_id:                    "" => ""
  tags.%:                       "" => "3"
  tags.App:                     "" => "ecommerce"
  tags.Environment:             "" => "Production 1"
  tags.Name:                    "" => "server-1"
  tenancy:                      "" => ""
  volume_tags.%:                "" => ""
  vpc_security_group_ids.#:     "" => ""
aws_instance.server[0]: Modifications complete after 4s (ID: i-052a34a0680983ae0)
aws_instance.server.1: Still creating... (10s elapsed)
aws_instance.server.1: Still creating... (20s elapsed)
aws_instance.server.1: Still creating... (30s elapsed)
aws_instance.server[1]: Creation complete after 36s (ID: i-04b7b0760c2ca8bee)
Apply complete! Resources: 1 added, 1 changed, 0 destroyed

Terraform обновляет состояние ресурсов, которыми она управляет, перед началом развертывания …

Добавьте эластичный IP-адрес ко всему созданного экземпляру. Поскольку мы создали только два экземпляра, мы добавим эластичный IP-адрес (EIP) к созданным экземплярам. Чтобы избежать повторения, мы будем использовать счетчик переменных и интерполировать его. … …

variable "counter" {
  description = "Specify the number of resources"
  default = 2
}

Создайте ресурс для eIP и синтаксического анализа переменной счетчика. Добавление resources.tf .

### This is just pseudo code. It won't actually work in Terraform.
for i = 0; i < 2; i++ {
  resource "aws_eip" "server" {
    instance = "${aws_instance.server.[i].id}"
  }
}
### This is a real code. It actually work in Terraform.
resource "aws_eip" "server" {
  count = "${var.counter}"
  instance = "${element(aws_instance.server.*.id, count.index)}"
}

… … и aws_instance.server.1.id который будет иметь идентификатор экземпляра i-04b7b0760c2ca8bee

$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.
aws_instance.server[0]: Refreshing state... (ID: i-052a34a0680983ae0)
aws_instance.server[1]: Refreshing state... (ID: i-04b7b0760c2ca8bee)
------------------------------------------------------------------------
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create
Terraform will perform the following actions:
+ aws_eip.server[0]
      id:                
      allocation_id:     
      association_id:    
      domain:            
      instance:          "i-052a34a0680983ae0"
      network_interface: 
      private_ip:        
      public_ip:         
      public_ipv4_pool:  
      vpc:               
+ aws_eip.server[1]
      id:                
      allocation_id:     
      association_id:    
      domain:            
      instance:          "i-04b7b0760c2ca8bee"
      network_interface: 
      private_ip:        
      public_ip:         
      public_ipv4_pool:  
      vpc:               
Plan: 2 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

Применить выходные данные слишком многословны, пусть ограничьте вывод только печатью общедоступного IP-адреса. Для этого создайте ...

## Limit the output to print out only the 
output "IP Address: " {
  value = ["${aws_instance.server.*.public_ip}"]
}
## pseudo code - DO NOT INCLUDE THE BELOW IN YOUR OUTPUT.TF
count = n
for i=0; i

$ terraform apply -auto-approve
aws_instance.server[0]: Refreshing state... (ID: i-052a34a0680983ae0)
aws_instance.server[1]: Refreshing state... (ID: i-04b7b0760c2ca8bee)
aws_eip.server[0]: Creating...
  allocation_id:     "" => ""
  association_id:    "" => ""
  domain:            "" => ""
  instance:          "" => "i-052a34a0680983ae0"
  network_interface: "" => ""
  private_ip:        "" => ""
  public_ip:         "" => ""
  public_ipv4_pool:  "" => ""
  vpc:               "" => ""
aws_eip.server[1]: Creating...
  allocation_id:     "" => ""
  association_id:    "" => ""
  domain:            "" => ""
  instance:          "" => "i-04b7b0760c2ca8bee"
  network_interface: "" => ""
  private_ip:        "" => ""
  public_ip:         "" => ""
  public_ipv4_pool:  "" => ""
  vpc:               "" => ""
aws_eip.server[0]: Creation complete after 2s (ID: eipalloc-0c07ddabca4380095)
aws_eip.server[1]: Creation complete after 2s (ID: eipalloc-030dbe801558ada64)
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Outputs:
IP Address:  = [
    18.213.188.193,
    54.83.98.206
]

Теперь, когда мы прикрепили эластичный IP-адрес к созданным экземплярам. Вы можете оптимизировать вывод. …

output "IP Address - Instance Name: " {
  value = ["${aws_instance.server.*.public_ip}", "-", "${aws_instance.server.*.tags.Name}"]
}
## pseudo code - DO NOT INCLUDE THE BELOW IN YOUR OUTPUT.TF
count = n
for i=0; i

Применять:

$ terraform apply -auto-approve
aws_instance.server[0]: Refreshing state... (ID: i-052a34a0680983ae0)
aws_instance.server[1]: Refreshing state... (ID: i-04b7b0760c2ca8bee)
aws_eip.server[1]: Refreshing state... (ID: eipalloc-030dbe801558ada64)
aws_eip.server[0]: Refreshing state... (ID: eipalloc-0c07ddabca4380095)
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
IP Address - Instance Name:  = [
    18.213.188.193,
    54.83.98.206,
    -,
    server-0,
    server-1
]

… Присоединение Route53 и ElasticLoadBalancer

Оригинал: «https://www.codementor.io/@bolatitokabir/terraform-part-ii-wn0235osm»