是否有可能在Ansible中执行if-else检查?

时间:2017-04-12 10:04:29

标签: amazon-ec2 ansible

目前,我的现场EC2配置游戏如下:

- name: Provisioning Spot instaces
  ec2:
    spot_price: 0.50
    spot_wait_timeout: 300
    assign_public_ip: no
    aws_access_key: "{{ aws_id }}"
    aws_secret_key: "{{ aws_key }}"
    region: "{{ aws_region }}"
    image: "{{ image_instance }}"
    instance_type: "{{ large_instance }}"
    key_name: "{{ ssh_keyname }}"
    count: 3
    state: present
    group_id: "{{ cypher_priv_sg }}"
    vpc_subnet_id: "{{ private_subnet_id }}"
    wait: true
    instance_tags:
      Name: Cypher-Worker
    #delete_on_termination: yes
  register: ec2

那么,是否可以执行以下操作:

在配置(点)EC2实例时,我想逐步检查(如(40%。50%,60%,70%..))如果全部失败,则创建一个按需实例。 我该怎么做?

我可以在这里使用Blocks功能吗?如果是,那怎么办?

2 个答案:

答案 0 :(得分:0)

示例:

shell: /some/command
register: result
when: ( result is not defined ) or ( result.rc != 0 )
with_items:
  - 40
  - 50
  - 60
  - 70
  - 100 # on-demand

这将运行包含所有列出项目的任务,直到其中一项成功为止。

UPD:这是shell模块的示例,我不知道ec2模块输出结构,不要使用它。对于shell模块,它可以正常工作。为什么要投票?

答案 1 :(得分:0)

这个怎么样:

 - name: Create ec2 instance
   ec2:
    key_name: "{{ key }}"
    group: "{{ group }}"
    instance_type: "{{ itype }}"
    image: "{{ image }}"
    region: "{{ region }}"
    wait: yes
    wait_timeout: 500
    volumes:
     - device_name: /dev/xvda
       volume_type: "{{ voltype }}"
       volume_size: "{{ volsize }}"
    monitoring: no
    vpc_subnet_id: "{{ subnetid }}"
   register: system

 - name: Wait for ssh
   wait_for: host={{ item.public_ip }} port=22 state=started
   with_items:
    - "{{ system.instances }}"

 - name: Name the new instance
   ec2_tag: resource={{ item.id }} region=eu-central-1 state=present
   args:
    tags:
     Name: "{{ name }}"
   with_items:
    - "{{ system.instances }}"

您(尝试)创建您的实例并将其事实存储在system中。如果您需要检查system是否实际包含您需要的内容,您只需添加when: system.instances.id[0] is defined,或者更进一步 - 检查您的新实例是否可以在端口22上访问,如上例所示。

您可以将这些条件检查用于其他任务,实现if-not逻辑 - 如果实例创建失败并且ssh无法访问它,则创建按需实例。

 - name: Wait for ssh
   wait_for: host={{ item.public_ip }} port=22 state=started
   with_items:
    - "{{ system.instances }}"
   register: result

下一步:

   when: '"ERROR" in result'
相关问题