使用Ansible创建AWS Application Load Balancer规则

时间:2018-02-01 15:59:48

标签: amazon-web-services ansible

我尝试使用Ansible为现有ALB上的未配置HTTP侦听器创建规则。我通过检索alb的事实来解决问题,然后使用这些事实来定义一个Ansible ALB资源,添加我想要的规则,但是我遇到了问题。

我希望Ansible循环遍历我的group_vars文件(它已成功完成其他任务)来创建这些多个规则。但是,在循环时,不是将规则附加到侦听器,而是销毁/创建它们。因此,当剧本完成时,您只剩下一个规则,引用vars文件末尾定义的任何项目(在我的案例中为Surrey)。

我的代码在下面(为了简洁起见,我已经排除了得到和设置事实的部分):

- name: Add HTTP listener rules
  elb_application_lb:
    state: present
    name: "{{ albinfo.load_balancer_name }}"
    subnets:
      - "{{ albinfo.availability_zones[0].subnet_id }}"
      - "{{ albinfo.availability_zones[1].subnet_id }}"
      - "{{ albinfo.availability_zones[2].subnet_id }}"
    security_groups:
      - "{{ albinfo.security_groups[0] }}"
    listeners:
      - Protocol: HTTP
        Port: 80
        DefaultActions:
          - Type: forward
            TargetGroupName: default
        Rules:
          - Conditions:
              - Field: host-header
                Values: "{{ item.url }}"
            Priority: "{{ item.priority }}"
            Actions:
              - TargetGroupName: "{{ item.name }}"
                Type: forward
    purge_listeners: no
  with_items: "{{ regions }}"

我的"地区" vars文件看起来像这样:

regions:
  - name: manchester
    priority: 1
    url:
      - manchester.example.com

  - name: surrey
    priority: 2
    url:
      - surrey.example.com

1 个答案:

答案 0 :(得分:1)

使用with_items迭代elb_application_lb模块的方式将无法正常工作。执行多个命令将产生最后一个命令将“赢”的效果,因为它将覆盖现有的elb规则集。

您需要做的是在对elb_application_lb的单个调用中定义每个规则,而不是对多个调用此模块的规则进行分层。您可以创建一个定义所有规则的dict,如下所示:

- name: Add HTTP listener rules
  elb_application_lb:
    state: present
    name: "{{ albinfo.load_balancer_name }}"
    subnets:
      - "{{ albinfo.availability_zones[0].subnet_id }}"
      - "{{ albinfo.availability_zones[1].subnet_id }}"
      - "{{ albinfo.availability_zones[2].subnet_id }}"
    security_groups:
      - "{{ albinfo.security_groups[0] }}"
    listeners:
      - Protocol: HTTP
        Port: 80
        DefaultActions:
          - Type: forward
            TargetGroupName: default
        Rules:
          - "{{ region_rules }}"
    purge_listeners: no

区域规则var如下所示:

    region_rules:
      - Conditions:
          - Field: host-header
            Values: manchester.example.com
        Priority: 1
        Actions:
          - TargetGroupName: manchester
            Type: forward

      - Conditions:
          - Field: host-header
            Values: surrey.example.com
        Priority: 2
        Actions:
          - TargetGroupName: surrey
            Type: forward