Shell没有输出时,Ansible寄存器失败

时间:2019-03-10 03:36:01

标签: ansible ansible-2.x

所以基本上我想以某种方式检查/ dev / xvdb1是否挂载到/ var

如果回答是:

  1. 不要创建目录
  2. 不复制文件
  3. 不要挂载/ var 等等

如果答案是否定的:

  1. 继续进行所有操作

    - name: check if /var is mounted
      shell: df -hT | grep /var
      register: df
    
    - name: Create /mnt/newvar directory
      file: 
        path: "{{ newvar_dir }}"
        state: directory
      when: not df.stdout_lines
    
    - name: "Get UUID for partition"
      shell: "lsblk -no UUID /dev/xvdb1"
      register: volume_uuids
    
    - name: Mount /mnt/newvar to /dev/xvdb1
      mount:
        path: "{{ newvar_dir }}"
        src: "UUID={{ item }}"
        fstype: "{{ volume_filesystem_type }}"
        opts: "defaults,noauto"
        state: mounted
      with_items: 
        - "{{ volume_uuids.stdout_lines }}"
      when: not df.stdout_lines
    

错误: 致命的:[x.x.x.x]:失败! => {“ changed”:true,“ cmd”:“ df -hT | grep / var”,“ delta”:“ 0:00:00.005132”,“ end”:“ 2019-03-10 03:07:22.485343 “,” msg“:”非零返回码“,” rc“:1,”开始“:” 2019-03-10 03:07:22.480211“,” stderr“:”“,” stderr_lines“:[] ,“ stdout”:“”,“ stdout_lines”:[]}

问题是:如果df命令没有输出,则制动器会刹车。

2 个答案:

答案 0 :(得分:0)

您可以ansible_mounts来查看安装是否存在,并set_fact来定义一个新变量,而不用使用df并注册结果。

请参阅下文以供参考:

- name: Check if /var mount exists
  set_fact:
    is_var_mounted: true
  when: item.mount == "/var"
  with_items: "{{ ansible_mounts }}"

- name: Do everything you want to do if not mounted
  debug:
     msg: "Doing Things"
  when: is_var_mounted is not defined

- name: Skip steps if mounted
  debug:
     msg: "Skipping"
  when: is_var_mounted is defined

答案 1 :(得分:0)

很有可能/ var不是挂载点,并且该命令返回1。

> df -hT | grep /var
> echo $?
1

这就是原因

Error: fatal: ... "msg": "non-zero return code", "rc": 1,

简单的条件是

when: /var in ansible_mounts|json_query('[].mount')