如何分配可跨任务使用的 ansible 变量?

如何分配可跨任务使用的 ansible 变量?

ansible 新手 - 我正在尝试根据主机 IP 地址的条件设置PS1变量。但我遇到了变量在任务间可用的问题。我不知道这是否是范围问题(据我所知/etc/bash.bashrcps1此链接)或者我是否应该有两个单独的剧本基本上做同样的事情(一个用于 LAN 主机,一个用于 WIFI 主机)。当我运行这个剧本时,我得到:

The task includes an option with an undefined variable. The error: 'dict object' has no attribute 'stdout'\n\n

有没有办法定义ps1变量,以便我可以将其分配到任务内部并供其他任务使用?

---
- hosts: all
  tasks:
    - name: generate LAN host bash prompt
      when: ansible_default_ipv4.address is match("192.168.16")
      connection: local
      shell : /usr/local/bin/psgen -l
      register: ps1
    - debug: var=ps1.stdout

    - name: generate WIFI host bash prompt
      when: ansible_default_ipv4.address is match("172.10.1")
      connection: local
      shell : /usr/local/bin/psgen -w
      register: ps1

    - name: write PS1 to remote /etc/bash.bashrc
      lineinfile:
        dest: /etc/bash.bashrc
        line: "{{ ps1.stdout }}"
        regexp: "PS1="
        insertafter: EOF

答案1

如果我要这样做,我不会添加任务。相反,我会删除一个任务,让你的任务变成一个循环。当你循环某个任务时,所有结果都会存储在一个列表中。然后,你可以使用各种 jinja 表达式从列表中提取成功的结果。

---
- hosts: all
  tasks:
  - name: generate host bash prompt
    when: ansible_default_ipv4.address is match(item.net_match)
    connection: local
    shell : "{{item.shell}}"
    register: ps1
    loop:
    - name: LAN
      shell: /usr/local/bin/psgen -l
      net_match: 192.168.16
    - name: WAN
      shell: /usr/local/bin/psgen -w
      net_match: 172.10.1

  - debug:
      msg: "ps1"
  - debug:
      msg: "{{ (ps1.results | selectattr('rc', 'defined') | list)[0].stdout }}"

  - name: write PS1 to remote /etc/bash.bashrc
    lineinfile:
      dest: /etc/bash.bashrc
      line: "{{ (ps1.results | selectattr('rc', 'defined') | list)[0].stdout }}"
      regexp: "PS1="
      insertafter: EOF

答案2

@Zoredache 是正确的。

从:http://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#registered-variables

如果任务失败或被跳过,变量仍然会注册为失败或跳过的状态,避免注册变量的唯一方法是使用标签。

这应该有效:

- name: lan
  set_fact:
    psgen_args: -l
  when: ansible_default_ipv4.address is match("192.168.16")

- name: wlan
  set_fact:
    psgen_args: -w
  when: ansible_default_ipv4.address is match("172.10.1")

- name: set ps1
  shell: /usr/local/bin/psgen {{ psgen_args }}
  register: ps1

- name: write PS1 to remote /etc/bash.bashrc
  lineinfile:
    dest: /etc/bash.bashrc
    line: "{{ ps1.stdout }}"
    regexp: "PS1="
    insertafter: EOF

相关内容