有条件的事实

ansible facts with condition

我正在尝试设置基于事实的输入变量。

if input protocol = to TCP/UDP 
  then service name will be TCP-443/UDP-443 
else service name will be ALL

我可以用下面的方法实现我的要求,但我想简化它,有人可以帮我吗

  - name: setting fact for service name
    set_fact:
      servicename: TCP-{{port}}
    when: >
          protocol == "TCP" or protocol == "tcp"

  - name: setting fact for service name
    set_fact:
      servicename: UDP-{{ port }}
    when: >
          protocol == "UDP" or protocol == "udp"

  - name: setting fact for service name
    set_fact:
      servicename: "ALL"
    when: >
          protocol == "all" or protocol == "ALL"

  - name: setting fact for service name
    set_fact:
      protocolname: "tcp_udp_sctp"
    when: >
          protocol == "TCP" or protocol == "tcp"

  - name: setting fact for service name
    set_fact:
      protocolname: "tcp_udp_sctp"
    when: >
          protocol == "UDP" or protocol == "udp"

  - name: setting fact for service name
    set_fact:
      protocolname: "ALL"
    when: >
          protocol == "all" or protocol == "ALL"

等价的如下,我觉得

  vars:
    port: 443
  tasks:
    - name: setting fact for service name
      set_fact:
        servicename: "{{ protocol|upper }}-{{ port }}"
        protocolname: "tcp_udp_sctp"
      when: protocol|upper == "TCP" or
            protocol|upper == "UDP"

    - name: setting fact for service name
      set_fact:
        servicename: "ALL"
        protocolname: "ALL"
      when: protocol|upper == "ALL"