Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

Ansible: Declaring vars that are accessible to entire play, under "tasks"

I'm trying to declare some variables based on a value returned by a task inside the play. This is what I have.

  tasks:
    - name: search for file
      find:
        paths: "{{path}}"
        patterns: "*{{pattern}}*"
        recurse: "yes"
        file_type: "file"
      register: result
      vars:
        file_path: result.files.0.path
        file_name: file_path.split("/")[-1]
        file_model: file_name.split("_")[0]
        file_version: file_name.split("_")[1]
    - debug:
        msg: "info: {{file_path}} : {{file_name}} : {{file_model}} : {{file_version}}"

Based on the undefined variable error thrown by the debug task, I assume variables declared underneath a task are scope limited to that specific task.

If so, is there any way to declare variables accessible to the entire play, underneath "tasks"?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this

  tasks:
    - name: search for file
      find:
        paths: "{{ path }}"
        patterns: "*{{ pattern }}*"
        recurse: yes
        file_type: file
      register: result
    - set_fact:
        file_path: "{{ result.files.0.path }}"
        file_name: "{{ file_path.split('/')[-1] }}"
        file_model: "{{ file_name.split('_')[0] }}"
        file_version: "{{ file_name.split('_')[1] }}"
    - debug:
        msg: "info: {{ file_path }} :
                    {{ file_name }} :
                    {{ file_model }} :
                    {{ file_version }}"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...