设置变量的行太长

Line too long for setting up variable

这是我的 Ansible 任务:

- name: get the custom job id
  ansible.builtin.set_fact:
    custom_job_id: >
      "{{ train_custom_image_unmanaged_response.stderr_lines |select('search', 'describe') |list |regex_search('.*/customJobs/(\d+)', '\1') |first }}"
  when: "(gcs_model_list.stdout is not defined) or ('saved_model.pb' not in gcs_model_list.stdout)"

我收到 “行太长” 作为 custom_job_id 行的 Ansible lint 错误。
知道如何将它分解成更小的部分吗?

您可以在开始时使用 YAML multi lines syntaxes 来完成。

使用此语法,缩进就是定义块的内容,因此,只要您在事实名称 custom_job_id 的内部缩进,以下所有代码都被视为要进行的表达式分配给那个事实。

例如:

- name: get the custom job id
  ansible.builtin.set_fact:
    custom_job_id: >-
      {{ 
        train_custom_image_unmanaged_response.stderr_lines 
        | select('search', 'describe') 
        | list 
        | regex_search('.*/customJobs/(\d+)', '') 
        | first 
      }}
  when: >- 
    gcs_model_list.stdout is not defined 
    or 'saved_model.pb' not in gcs_model_list.stdout

这是一个符合 Ansible linting 的剧本,证明了这一点:

- hosts: localhost
  gather_facts: true

  tasks:
    - name: Get the custom job id
      ansible.builtin.set_fact:
        custom_job_id: >-
          {{
            train_custom_image_unmanaged_response.stderr_lines
            | select('search', 'describe')
            | list
            | regex_search('.*/customJobs/(\d+)', '')
            | first
          }}
      when: >-
        gcs_model_list.stdout is not defined
        or 'saved_model.pb' not in gcs_model_list.stdout
      vars:
        train_custom_image_unmanaged_response:
          stderr_lines:
            - foo
            - bar
            - describe - /customJobs/123
            - baz
        gcs_model_list:

    - name: Display `custom_job_id`
      ansible.builtin.debug:
        var: custom_job_id

产生:

PLAY [localhost] **********************************************************

TASK [Get the custom job id] **********************************************
ok: [localhost]

TASK [Display `custom_job_id`] ********************************************
ok: [localhost] => 
  custom_job_id: '123'