Ansible 未定义变量

Ansible 未定义变量

我正在使用 ansible [core 2.11.10] 并且我最近制作了以下 yaml 文件:

- name: Linux Security Patching Playbook
  hosts: Linux_NPROD
  become: true
  become_user: root
  vars:
    ansible_python_interpreter: auto_silent
  tasks:
    - name : " Debian / Ubuntu Patching "
      shell : 'grep security /etc/apt/sources.list > /tmp/security.list && sudo apt-get upgrade -oDir::Etc::Sourcelist=/tmp/security.list -s'
      register: response
      when : ansible_os_family == "Debian" or ansible_os_family == "Ubuntu"
    - debug: msg="{{ response.stdout }}"

    - name: " CentOS / RHEL Patching "
      shell : 'yum update --security'
      register: x
      when : ansible_os_family == "RedHat"
    - debug: msg="{{ x.stdout }}"

输出在“Debian / Ubuntu Patching”任务中工作正常,但在第二个任务中我收到以下错误:

致命:[]:失败! => {“msg”:“该任务包含一个带有未定义变量的选项。错误是:'dict object'没有属性'stdout'\n\n错误似乎位于'/home/superuser/Ansible/playbooks /security_patching.yaml':第 18 行,第 7 列,但\n可能位于文件中的其他位置,具体取决于具体的语法问题。\n\n有问题的行似乎是:\n\n 当:ansible_os_family == "RedHat"\ n - debug: msg="{{ x.stdout }}"\n ^ 这里\n我们可能是错的,但这看起来可能是一个问题\n在开始时总是引用模板表达式括号。例如:\n\n with_items:\n - {{ foo }}\n\n应写为:\n\n with_items:\n - "{{ foo }}"\n"}

当我像这样修改 yaml 文件时,会发生同样的错误:

- name: Linux Security Patching Playbook
  hosts: Linux_NPROD
  gather_facts: true
  become: true
  become_user: root
  vars:
    ansible_python_interpreter: auto_silent
  tasks:
    - name : " Debian / Ubuntu Patching "
      shell : 'grep security /etc/apt/sources.list > /tmp/security.list && sudo apt-get upgrade -oDir::Etc::Sourcelist=/tmp/security.list -s'
      register: response
      when : ansible_os_family == "Debian" or ansible_os_family == "Ubuntu"
    - debug: msg="{{ response.stdout }}"

    - name: " CentOS Patching "
      yum:
       security: yes
       state: latest
      check_mode: yes
      register: yum_output
      become: true
      when : ansible_os_family == "RedHat"
    - debug: msg="{{ yum_output.stdout }}"

在最后一个 yaml 文件中,如果我对第一个任务发表评论,那么第二个任务就可以正常工作。

我有什么想法可以解决这个错误吗?

答案1

像这样的任务

- name: "CentOS / RHEL command"
  shell:
    cmd: 'echo "I was running"' 
  register: result
  when: ansible_os_family == "RedHat"

根据事实执行或跳过。所以登记结果仅当条件为真时才会发生。

我有什么想法可以解决这个错误吗?

为了不让下一个任务失败,该任务将依赖于注册变量的存在,可以以不同的方式解决这个问题。

通过添加与之前任务相同的条件

- name: Show result
  debug: 
    msg: "{{ result.stdout }}"
  when: ansible_os_family == "RedHat"

通过添加一个基于变量的条件

  when: result.stdout is defined

通过增加默认价值观

- name: Show result
  debug: 
    msg: "{{ result.stdout | default('I was not running') }}"

经过用块对任务进行分组如果条件为真,则将它们一起执行。

如果适用,通过寻址check_mode

- name: Show result
  debug: 
    msg: "{{ result.stdout | default('I was not running') }}"
  when: not ansible_check_mode

check_mode: false因为如果未设置,前一个任务可能不会运行,因此也没有注册结果。

相关内容