Ansible: Create instances in different subnets

空扰寡人 提交于 2020-01-17 05:30:30

问题


I'm trying to use Ansible to create two instances, one each in two subnets using the play below. I'm using exact_count with tag Name to keep track of instances. There are two issues here:

  1. Ansible ends up creating two instances in the first subnet and reports [ok] for the second subnet.
  2. Ansible doesn't seem to care about stopped instances. It creates new instances, instead of starting existing ones, or atleast considering them as part of the group of instances.
  - name: Create kafka instances
    with_items:
      - "{{ vpc_pvt_subnet_2 }}"
      - "{{ vpc_pvt_subnet_1 }}"
    ec2:    
      group: "{{ kafka_sg }}"  
      key_name: "{{ ec2_keypair }}"  
      region: "{{ region }}"  
      image: "{{ ami_id }}"  
      wait: true   
      instance_type: "{{ kafka_inst_type }}"  
      vpc_subnet_id: "{{ item }}"  
      instance_tags:  
        Name: "kafka-instance"          
        Owner: data  
      exact_count: 2   
      count_tag:  
        Name: "kafka-instance"  
    register: ec2

Can someone please tell me what's wrong with the playbook here?


回答1:


Assuming that you want to create 1 EC2 instance in each subnet, one visible error in the snippet you provided is that the value of exact_count should be set to 1 (not 2) because with_items will loop to run ec2 module twice in your playbook. You want each iteration to create exactly 1 instance.

Next, I will answer according to your questions -

1] You need to specify zone parameter as well to ec2 module. Since zone is dynamic according to a vpc_subnet_id, I would suggest the following structure -

In your vars -

subnets:
  - { zone: "us-east-1a", vpc_pvt_subnet: "subnet-abcdafa5"}
  - { zone: "us-east-1b", vpc_pvt_subnet: "subnet-zyxwvb51"}

In the ec2 task -

- name: "Create kafka instances"
  with_items: "{{ subnets }}"
  ec2:
    group: "{{ kafka_sg }}"
    key_name: "{{ ec2_keypair }}"
    region: "{{ region }}"
    image: "{{ ami_id }}"
    wait: true
    instance_type: "{{ kafka_inst_type }}"
    vpc_subnet_id: "{{ item.vpc_pvt_subnet }}"
    zone: "{{ item.zone }}"
    instance_tags:
      Name: "kafka-instance"
      Owner: "data"
    exact_count: 1
    count_tag:
      Name: "kafka-instance"
  register: ec2

2] Yes, the above way will always create new instance even if an instance already exists in a subnet with "stopped" state as if this instance never existed. If you want to explicitly start the "stopped" instances by tags, you can achieve that by passing the state parameter to a new ec2 task - you cannot use state and exact_count parameters together in the same task.

Hope this helps!



来源:https://stackoverflow.com/questions/37502494/ansible-create-instances-in-different-subnets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!