ansible register

 在 Ansible 中,register 用于 存储任务的输出结果,以便后续任务可以引用或使用这个结果。它是 Playbook 中的一个关键功能,特别适用于需要条件判断依赖上一步执行结果的场景。

如何查看模块返回的字段信息

1. debug: var=变量名 直接查看 register 变量。

    - name: 创建文件
      ansible.builtin.file:
        path: "/tmp/111222.txt"
        state: touch
      register: file_check

    - name: 显示标准输出
      debug:
        var: file_check

输出

ok: [192.168.43.130] => {
    "file_check": {
        "changed": true,                 # 可以根据这个字段进行判断
        "dest": "/tmp/111222.txt",
        "diff": {
            "after": {
                "atime": 1740126955.02548,
                "mtime": 1740126955.02548,
                "path": "/tmp/111222.txt",
                "state": "touch"
            },
            "before": {
                "atime": 1740126610.4133165,
                "mtime": 1740126610.4133165,
                "path": "/tmp/111222.txt",
                "state": "file"
            }
        },
        "failed": false,
        "gid": 0,
        "group": "root",
        "mode": "0644",
        "owner": "root",
        "size": 0,
        "state": "file",
        "uid": 0
    }
}

2. 查看模块帮助信息

shell模块

ansible-doc shell


RETURN VALUES:

msg:
    description: changed
    returned: always
    type: bool
    sample: True
start:
    description: The command execution start time
    returned: always
    type: str
    sample: '2016-02-25 09:18:26.429568'
end:
    description: The command execution end time
    returned: always
    type: str
    sample: '2016-02-25 09:18:26.755339'
delta:
    description: The command execution delta time
    returned: always
    type: str
    sample: '0:00:00.325771'
stdout:
    description: The command standard output
    returned: always
    type: str
    sample: 'Clustering node rabbit@slave1 with rabbit@master ...'
stderr:
    description: The command standard error
    returned: always
    type: str
    sample: 'ls: cannot access foo: No such file or directory'
cmd:
    description: The command executed by the task
    returned: always
    type: str
    sample: 'rabbitmqctl join_cluster rabbit@master'
rc:
    description: The command return code (0 means success)
    returned: always
    type: int
    sample: 0
stdout_lines:
    description: The command standard output split in lines
    returned: always
    type: list
    sample: [u'Clustering node rabbit@slave1 with rabbit@master ...']

 

uri模块

ansible-doc uri

RETURN VALUES:

# The return information includes all the HTTP headers in lower-case.
elapsed:
  description: The number of seconds that elapsed while performing the download
  returned: on success
  type: int
  sample: 23
msg:
  description: The HTTP message from the request
  returned: always
  type: str
  sample: OK (unknown bytes)
redirected:
  description: Whether the request was redirected
  returned: on success
  type: bool
  sample: false
status:
  description: The HTTP status code from the request
  returned: always
  type: int
  sample: 200
url:
  description: The actual URL used for the request
  returned: always
  type: str
  sample: https://www.ansible.com/

stat模块

ansible-doc  stat

register 的基本用法

1. 存储 command 执行结果

- hosts: all
  tasks:
    - name: 获取主机名
      command: hostname
      register: result

    - name: 显示主机名
      debug:
        var: result.stdout

🔹 解释

  1. command: hostname 获取当前主机的主机名。
  2. register: result 把任务的执行结果存入 result 变量。
  3. debug: var=result.stdout 显示 result 变量中的 stdout(标准输出)。

 运行结果

TASK [显示主机名] ********************
ok: [server1] => {
    "result.stdout": "server1"
}

2. register 变量的结构

register 存储的内容是一个 字典,包含多个字段,例如:

- name: 获取文件列表
  command: ls /etc
  register: file_list

 存储的 file_list 变量结构:

{
    "changed": true,
    "cmd": ["ls", "/etc"],
    "stdout": "passwd\nshadow\nhosts",
    "stderr": "",
    "rc": 0
}

常用字段:

字段含义
stdout 标准输出(结果)
stderr 标准错误输出
rc 返回码(0 表示成功)
changed 是否发生变更

 

3.register + when 条件判断

只有 myfile.txt 存在时才执行后续任务

- hosts: all
  tasks:
    - name: 检查文件是否存在
      stat:
        path: /tmp/myfile.txt
      register: file_status

    - name: 读取文件内容(如果文件存在)
      command: cat /tmp/myfile.txt
      when: file_status.stat.exists

解释

  1. stat 模块检查 /tmp/myfile.txt 是否存在,并将结果存入 file_status
  2. when: file_status.stat.exists 确保只有当文件存在时才执行 cat 命令。

4. register + with_items(循环)

📌 示例:批量检查多个文件是否存在

- hosts: all
  tasks:
    - name: 检查多个文件
      stat:
        path: "{{ item }}"
      register: file_status
      with_items:
        - /etc/passwd
        - /etc/hosts
        - /tmp/nonexistent.txt

    - name: 显示哪些文件存在
      debug:
        msg: "文件 {{ item.item }} 存在"
      when: item.stat.exists
      with_items: "{{ file_status.results }}"

🔹 解释

  • file_status.resultsstat 任务返回的列表,每个元素包含 stat.exists
  • when: item.stat.exists 过滤出存在的文件。

示例输出

TASK [显示哪些文件存在] ***********
ok: [server1] => (item=/etc/passwd) => {
    "msg": "文件 /etc/passwd 存在"
}
ok: [server1] => (item=/etc/hosts) => {
    "msg": "文件 /etc/hosts 存在"
}

5. register + failed_when 自定义失败条件

📌 示例:允许 ping 失败,但 5% 以上丢包则任务失败

- hosts: all
  tasks:
    - name: 执行 ping 测试
      command: ping -c 5 google.com
      register: ping_result
      failed_when: "'100% packet loss' in ping_result.stdout"

解释

  • failed_when 让任务在 100% packet loss 出现时才被判定为失败。

总结

功能示例
存储命令输出 register: result
访问 stdout result.stdout
条件判断 when: result.rc == 0
结合循环 with_items: "{{ result.results }}"
自定义失败条件 failed_when: "'error' in result.stderr"
对于 ansible.builtin.uri 模块,它返回的数据结构包含多个字段,你可以从中提取所需的信息。

1. ansible.builtin.uri 返回的 register 变量结构

- name: check nginx port
  ansible.builtin.uri:
    url: http://localhost:{{ listen_port }}
    status_code: 200
  register: result

2.  如果 listen_port = 80,请求 http://localhost:80,任务执行后 result 变量的典型值如下:

{
    "changed": false,
    "failed": false,
    "msg": "OK",
    "redirected": false,
    "status": 200,
    "json": null,
    "content_length": "612",
    "cookies": {},
    "cookies_string": "",
    "date": "Tue, 20 Feb 2024 10:00:00 GMT",
    "elapsed": 0,
    "server": "nginx",
    "url": "http://localhost:80"
}

 3. ansible.builtin.uri 可用的 register 变量字段

- debug:
    var: result

🔹 你可以使用的字段包括:

字段描述
result.status HTTP 状态码(如 200404500
result.json JSON 响应数据(如果返回的是 JSON)
result.content_length 响应的内容长度
result.cookies 响应的 cookies(如果有的话)
result.server 服务器的 Server 头信息(如 "nginx"
result.elapsed 请求花费的时间(秒)
result.url 最终访问的 URL(如果有跳转)

 4. until + retries + delay 配合使用

如果服务器启动可能需要时间,可以增加 retriesdelay

- name: check nginx port
  ansible.builtin.uri:
    url: http://localhost:{{ listen_port }}
    status_code: 200
  register: result
  retries: 5      # 最多重试 5 次
  delay: 2        # 每次重试间隔 2 秒
  until: result.status == 200

 这样如果 Nginx 启动较慢,Ansible 会等待最多 10 秒(5 次 × 2 秒)。

5. 访问 JSON 数据

如果服务器返回 JSON 格式的数据:

{
    "status": "ok",
    "version": "1.2.3"
}

 你可以这样获取:

- name: 获取 API 状态
  ansible.builtin.uri:
    url: http://localhost:{{ listen_port }}/api/status
    return_content: yes
  register: api_result

- name: 检查 API 版本
  debug:
    msg: "API 版本是 {{ api_result.json.version }}"

 

posted @ 2025-02-21 15:18  不会跳舞的胖子  阅读(63)  评论(0)    收藏  举报