查找语法中的Ansible变量

时间:2018-09-25 20:24:19

标签: ansible

我当前正在使用k8s查找来搜索带有附加特定标签的资源(在本例中为branch)。 branch是一个定期更改的变量。问题是我似乎找不到用于将变量添加到lookup的正确语法,因为它本身使用的是Jinja语法。

这有效:

  - name: delete the replicaset
    k8s:
      state: absent
      api_version: v1
      kind: ReplicaSet
      namespace: default
      name: "{{ replicaset.metadata.name }}"
      kubeconfig: /var/lib/awx/.kube/config
    vars:
      replicaset: "{{ lookup('k8s', kind='ReplicaSet', namespace='default', label_selector='branch=testing' ) }}"

但是,当尝试使用branch变量时,我尝试执行的操作似乎无效。这是一个无法正常工作的示例:

  - name: delete the replicaset
    k8s:
      state: absent
      api_version: v1
      kind: ReplicaSet
      namespace: default
      name: "{{ replicaset.metadata.name }}"
      kubeconfig: /var/lib/awx/.kube/config
    vars:
      replicaset: "{{ lookup('k8s', kind='ReplicaSet', namespace='default', label_selector='branch={{ branch }}' ) }}"

1 个答案:

答案 0 :(得分:0)

您可以添加一个辅助变量:

- name: delete the replicaset
  k8s:
    state: absent
    api_version: v1
    kind: ReplicaSet
    namespace: default
    name: "{{ replicaset.metadata.name }}"
    kubeconfig: /var/lib/awx/.kube/config
  vars:
    replicaset: "{{ lookup('k8s', kind='ReplicaSet', namespace='default', label_selector=my_selector ) }}"
    my_selector: branch={{ branch }}

或使用Jinja2字符串串联:

    replicaset: "{{ lookup('k8s', kind='ReplicaSet', namespace='default', label_selector='branch='+branch ) }}"