2016-02-11 161 views
0

您好我需要編寫一個Ansible代碼來啓動EC2實例並以循環方式將其分配給可用子網。手動創建的VPC只有1個,但根據啓動的基礎設施,子網的數量會有所不同。 我的hosts文件看起來像這樣使用Ansible啓動EC2實例並動態分配子網

[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}}" 

有一個不太混亂的方式來實現這一目標?

回答

1

您的playbook合併了兩個任務,因此當您嘗試運行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 loop循環訪問該子網ID列表以及實例列表。

+0

非常感謝:) – mp123