在 Ansible 中,如何在一个任务中导出环境变量以便它可以被另一个任务使用?

In Ansible, how do I export an environment variable in one task so it can be used by another task?

假设我有以下文件

foo.txt
Hello world=1
Hello world=2
...
Hello world=N

我想使用 Ansible 插入另一个 Hello world 行,像这样

foo.txt
Hello world=1
Hello world=2
...
Hello world=N
Hello world=N+1

IOW,我不知道家里有多少 Hello world 行,我需要通过脚本查找,并获取 N 的值。

在 Ansible 中,假设我有以下 shell 任务

- name: Find the last Hello world in foo.txt, and get the value of N
  shell: >
    # Get last Hello world line in foo.txt. I want to export this as an
    # environment variable
    LAST_HW_LINE=`awk '/Hello world/ {aline=[=12=]} END{print aline}' "foo.txt"`
    # Get left side of equation
    IFS='=' read -ra LS <<< "$LAST_HW_LINE"
    # Get the value of N
    NUM=${LS##*\.}
    # Increment by 1. I want to export this as an environment variable
    NUM=$((NUM+1))

我希望以后能够这样做

- name: Add the next Hello world line
  lineinfile:
    dest: foo.txt
    insertafter: "{{ lookup('env', 'LAST_HW_LINE') }}"
    line: "Hello world={{ lookup('env', 'NUM') }}"

也许有比使用环境变量更好的方法?

Register Variables

- shell: /usr/bin/foo
  register: foo_result

Registering stdout as ansible variables

- debug: msg="{{ hello.stdout }}"    
- debug: msg="{{ hello.stderr }}"

Including task with variables:

tasks:
  - include: wordpress.yml wp_user=timmy

Including role with variables

- hosts: webservers
  roles:
    - common
    - { role: foo_app_instance, dir: '/opt/a',  app_port: 5000 }

针对您的情况:

- name: so question 39041208
  hosts: '{{ target | default("all") }}'
  tasks:
  - name: Find the last Hello world in foo.txt, and get the value of N
#    shell: awk '/Hello world/ {aline=[=14=]} END{print aline}' "/home/ak/ansible/Whosebug/q39041208.txt"
    shell: awk '/Hello world/ {aline=[=14=]} END{print NR}' "/home/ak/ansible/Whosebug/q39041208.txt"
    register: last_line
    ignore_errors: true
  - name: debug
    debug: msg="last line {{ last_line.stdout }}"
  - name: debug next number
    debug: msg="next num {{ last_line.stdout | int + 1 }}"
  - name: Add the next Hello world line
    lineinfile:
      dest: /home/ak/ansible/Whosebug/q39041208.txt
      insertafter: "{{ last_line.stdout }}"
      line: "Hello world={{ last_line.stdout | int + 1 }}"