繁体   English   中英

在 Ansible 中的任务之间重用环境变量

[英]Reusing environment variables between tasks in Ansible

我正在运行 bash 脚本并注册其 output 的剧本中运行一些任务:

playbook.yml

- name: Compare FOO to BAZ
  shell: . script.sh
  register: output

- name: Print the generated output
  debug:
    msg: "The output is {{ output }}"
    
- include: Run if BAZ is true
  when: output.stdout == "true"

script.sh

#!/bin/bash
FOO=$(curl example.com/file.txt)
BAR=$(cat file2.txt)
if [ $FOO == $BAR ]; then
  export BAZ=true
else
  export BAZ=false
fi

发生的情况是 Ansible 注册了FOO=$(curl example.com/file.txt)的 output 而不是export BAZ

有没有办法注册BAZ而不是FOO

我尝试运行另一个可以获得导出值的任务:

- name: Register value of BAZ
  shell: echo $BAZ
  register: output

但是后来我意识到每个任务都会在远程主机上打开一个单独的 shell 并且无法访问在前面的步骤中导出的变量。

还有其他方法可以将正确的 output 注册为变量吗?

我想出了一个解决方法,但必须有另一种方法来做到这一点......

我在script.sh中添加了一行,并在单独的任务中对文件进行了分类

脚本.sh:

...
echo $BAZ > ~/baz.txt

然后在 playbook.yml 中:

- name: Check value of BAZ
  shell: cat ~/baz.txt
  register: output

这看起来有点像用锤子打螺丝……或者用螺丝刀种钉子。 决定是否要使用钉子或螺钉,然后使用适当的工具。

你的问题遗漏了很多细节,所以我希望我的回答不会离你的要求太远。 同时,这是一个(未经测试且非常通用)示例,使用 ansible 比较您的文件并根据结果运行任务:

- name: compare files and run task (or not...)
  hosts: my_group

  vars:
    reference_url: https://example.com/file.txt
    compared_file_path: /path/on/target/to/file2.txt

    # Next var will only be defined when the two tasks below have run
    file_matches: "{{ reference.content == (compared.content | b64decode) }}"

  tasks:
    - name: Get reference once for all hosts in play
      uri:
        url: "{{ reference_url }}"
        return_content: true
      register: reference
      delegate_to: localhost
      run_once: true

    - name: slurp file to compare from each host in play
      slurp:
        path: "{{ compared_file_path }}"
      register: compared

    - name: run a task on each target host if compared is different
      debug:
        msg: "compared file is different"
      when: not file_matches | bool 
        

万一您这样做只是为了检查文件是否需要更新,则无需费心:只需在目标上下载文件即可。 只有在需要时才会更换。 如果(且仅当)文件在目标服务器上实际更新时,您甚至可以在剧本末尾启动一个操作。

- name: Update file from reference if needed
  hosts: my_group

  vars:
    reference_url: https://example.com/file.txt
    target_file_path: /path/on/target/to/file2.txt

  tasks:
    - name: Update file on target if needed and notify handler if changed
      get_url:
        url: "{{ reference_url }}"
        dest: "{{ target_file_path }}"
      notify: do_something_if_changed

  handlers:
    - name: do whatever task is needed if file was updated
      debug:
        msg: "file was updated: doing some work"
      listen: do_something_if_changed

关于上述概念的一些参考 go :

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM