变量定义

1.访问变量文件

---
- hosts: frame
  remote_user: root
  gather_facts: no
  vars_files:
  - /testdir/ansible/testfile.txt
  tasks:
  - debug:
      msg: "{{key_1}}"

变量文件:

[root@frontend-1 mytestvar]# cat /testdir/ansible/testfile.txt
key_1: values_1

2.判断文件是否存在

---
- hosts: frame
  tasks:
  - name: check wheather  file exist
    shell: ls   /etc/hosts
    register: ls_result
  - name: when last step succeed , echo ok into file /tmp/1025/hosts
    shell: echo 'ok'  > /tmp/1025/hosts
    when: ls_result.rc == 0

 3.把变量的信息输出

-name: test
shell: echo 'hello world'
- debug: var=PermitRootLogin
TASK [debug] **********************************************************************************************************************************************************************************
ok: [10.0.0.4] => {
    "PermitRootLogin": {
        "changed": true,
        "cmd": "egrep 'PermitRootLogin yes' /etc/ssh/sshd_config|wc -l",
        "delta": "0:00:00.052518",
        "end": "2020-11-01 00:05:11.867289",
        "failed": false,
        "rc": 0,
        "start": "2020-11-01 00:05:11.814771",
        "stderr": "",
        "stderr_lines": [],
        "stdout": "1",
        "stdout_lines": [
            "1"
        ]
    }
}

 4. cat a.j2

{{ PermitRootLogin['stdout_lines'][0]|type_debug }}

 5.ignore_errors

- hosts: web_servers

  tasks:

     - name: Run a shell command and register its output as a variable
       ansible.builtin.shell: /usr/bin/foo
       register: foo_result
       ignore_errors: true

     - name: Run a shell command using output of the previous task
       ansible.builtin.shell: /usr/bin/bar
       when: foo_result.rc == 5
用一个例子来演示会更加清晰
原文地址:https://www.cnblogs.com/hixiaowei/p/13873110.html