簡體   English   中英

使用Ansible啟動EC2實例並動態分配子網

[英]Launch EC2 instances using Ansible and assign subnets dynamically

嗨,我有一個要求編寫Ansible代碼來啟動EC2實例,並以循環方式將它們分配給可用的子網。 手動創建的VPC只有1個,但是子網的數量會根據啟動的基礎架構而變化。 我的主機文件看起來像這樣

[ABC-database]
ABCDB01

[ABC-application]
ABCFE0[1:2]
ABCBE0[1:2]

[cassandra]
CASS0[1:3]

我還編寫了代碼來創建子網文件

subnet1: subnet-7284c12b
subnet2: subnet-fd363e98
subnet3: subnet-c892bfbf

我要做的是一次拾取一個實例,從all.yml中拾取每個實例的配置,並以循環(循環)的方式將其分配給每個子網。

目前,我已經編寫了一個Shell腳本來執行此操作。 該腳本會計算子網文件中的子網數量,並在每次調用時返回一個新的子網ID。

我被困在這之后。 啟動ec2實例時應如何調用此腳本? 下面的代碼引發錯誤“ next_subnet”未定義

- name: Launch instances.
  local_action:
    command: ./get_next_available_subnet.sh
    register: next_subnet
    module: ec2
    region: "{{ region }}"
    keypair: "{{ keypair }}"
    instance_type: "{{item.instance_type}}"
    image: "{{image_id}}"
    vpc_subnet_id: "{{ next_subnet.stdout }}"
    count: 1
    wait: yes
  with_items: "{{component_list}}"

有沒有一個比較簡單的方法來實現這一目標?

您的劇本將兩個任務合並為一個,因此當您嘗試運行ec2任務時, next_subnet變量未注冊。

將您的劇本更改為此可以解決當前的問題:

- name: Get next subnet
  local_action:
    command: ./get_next_available_subnet.sh
    register: next_subnet

- name: Launch instances
  local_action:
    ec2:
      region: "{{ region }}"
      keypair: "{{ keypair }}"
      instance_type: "{{item.instance_type}}"
      image: "{{image_id}}"
      vpc_subnet_id: "{{ next_subnet.stdout }}"
      count: 1
      wait: yes
  with_items: "{{component_list}}"

但是,那只會使劇本運行,而不是您想要的那樣。 如果您增加count數量,則每個實例仍將放置在同一個子網中,而next_subnet變量僅被注冊一次,然后在循環中使用它。

假設您可以不斷地反復調用腳本,並且腳本會在可用的子網ID中循環顯示,那么您只需要迭代第一個任務即可獲得結果列表,您可以將其與第二個任務一起使用,如下所示:

- name: Get next subnet
  local_action:
    command: ./get_next_available_subnet.sh
    register: next_subnet
  with_items: component_list

- name: Launch instances
  local_action:
    ec2:
      region: "{{ region }}"
      keypair: "{{ keypair }}"
      instance_type: "{{item.1.instance_type}}"
      image: "{{image_id}}"
      vpc_subnet_id: "{{ item.0.stdout }}"
      count: 1
      wait: yes
  with_together: 
    - next_subnet
    - component_list

假設您的shell腳本輸出如下所示:

$ ./get_next_available_subnet.sh
subnet-7284c12b
$ ./get_next_available_subnet.sh
subnet-fd363e98
$ ./get_next_available_subnet.sh
subnet-c892bfbf
$ ./get_next_available_subnet.sh
subnet-7284c12b

然后,第一個任務將使用任務結果列表注冊next_subnet變量,該任務結果列表將具有stdout鍵和子網ID的值。 然后,第二個任務使用with_together循環遍歷該子網ID列表以及實例列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM