kubernetes Ansible变量到int的转换被忽略

fafcakar  于 12个月前  发布在  Kubernetes
关注(0)|答案(1)|浏览(138)

使用Ansible,我希望找到K8s集群上某个范围内可用的端口,并使用此端口公开临时服务。
我能够找到并提取端口,但当我使用该端口声明Nodeport时,任务失败。
看起来ansible没有用指令{{ port}将我的“port”变量转换为int| int }}。

- block:
    - name: List all ports in range 32200 to 32220
      wait_for:
        port: "{{ item|int }}"
        timeout: 1
        state: stopped
        msg: "Port {{ item }} is already in use"
      register: available_ports
      with_sequence: start=32200 end=32220
      ignore_errors: yes

    - name: extract first unused port from list
      set_fact:
        port: "{{ available_ports.results | json_query(\"[? state=='stopped'].port\") | first }}"
    
- debug:
        var: port
    
- name: Expose service as a nodeport service
  k8s:
    state: present
    definition:
      apiVersion: v1
      kind: Service
      metadata:
        name: "{{ namespace }}-service-nodeport"
        namespace: "{{ namespace }}"
      spec:
        type: NodePort
        selector:
          component: my-app
        ports:
          - protocol: TCP
            targetPort: 5432
            nodePort: "{{ port|int }}"
            port: 5432

字符串
这将输出以下内容:

TASK [../roles/my-role : debug] ***************************************************************************************************************************************************************************************************
ok: [127.0.0.1] => {
    "port": "32380"
}

TASK [../roles/my-role : Expose service as a nodeport service] *******************************************************************************************************************************************
fatal: [127.0.0.1]: FAILED! => {"changed": false, "error": 400, "msg": "Failed to create object: b'{\"kind\":\"Status\",\"apiVersion\":\"v1\",\"metadata\":{},\"status\":\"Failure\",\"message\":\"Service in version \\\\\"v1\\\\\" cannot be handled as a Service: v1.Service.Spec: v1.ServiceSpec.Ports: []v1.ServicePort: v1.ServicePort.NodePort: readUint32: unexpected character: \\\\ufffd, error found in #10 byte of ...|dePort\\\\\": \\\\\"32380\\\\\", \\\\\"p|..., bigger context ...|rotocol\\\\\": \\\\\"TCP\\\\\", \\\\\"targetPort\\\\\": 5432, \\\\\"nodePort\\\\\": \\\\\"32380\\\\\", \\\\\"port\\\\\": 5432}]}}|...\",\"reason\":\"BadRequest\",\"code\":400}\\n'", "reason": "Bad Request", "status": 400}


如果我将nodeport设置为固定值,例如32800,它就可以工作。

cs7cruho

cs7cruho1#

也许这不是你的问题,但我解决了我的问题。
我把变量放在一个map中,所有的vars都放在字符串中.因为k8s是用GO写的,所以你不能有多类型的map,所以试着把你的变量移到另一个地方。

相关问题