linux Ansible playbook验证目录并检索服务器主机名或IP,如果不是空的[关闭]

2jcobegt  于 2023-06-05  发布在  Linux
关注(0)|答案(2)|浏览(203)

已关闭,此问题需要details or clarity。目前不接受答复。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

2天前关闭。
Improve this question
我想用ansible检查一个目录是否不为空。如果目录不为空,我希望获得服务器主机名或IP地址。谁能帮帮我?谢谢!
我想做个测试。

- hosts: all
  tasks:
  - find :
      paths: /tmp/foo
      file_type: all
      hidden: true
    register: out

  - fail :
      msg: the /tmp/foo directory is not empty
    when: out.matched != 0
whlutmcx

whlutmcx1#

Q:***“检查目录,如果为空则列出服务器。"***
答:有两个非常有用的模式,你应该一步一步地去了解细节。
例如,给定两个远程主机,第二个主机上的目录为空

shell> ssh admin@test_11 find /tmp/test_dir
/tmp/test_dir
/tmp/test_dir/bar
/tmp/test_dir/foo
shell> ssh admin@test_13 find /tmp/test_dir
/tmp/test_dir

找到文件

- find:
        paths: /tmp/test_dir
        file_type: any
        hidden: true
      register: out

1.克里特岛事实词典

report: "{{ dict(ansible_play_hosts|
                   zip(ansible_play_hosts|
                       map('extract', hostvars, ['out', 'matched']))) }}"

给予

report:
    test_11: 2
    test_13: 0

1.从字典中选择/拒绝属性并获取与条件匹配的属性的名称

empty: "{{ report|dict2items|
             rejectattr('value')|
             map(attribute='key') }}"

给你想要的

empty:
    - test_13

完整的测试剧本示例

- hosts: all

  vars:

    report: "{{ dict(ansible_play_hosts|
                     zip(ansible_play_hosts|
                         map('extract', hostvars, ['out', 'matched']))) }}"
    empty: "{{ report|dict2items|
               rejectattr('value')|
               map(attribute='key') }}"

  tasks:

    - find:
        paths: /tmp/test_dir
        file_type: any
        hidden: true
      register: out

    - debug:
        var: report
      run_once: true

    - debug:
        var: empty
      run_once: true
7fhtutme

7fhtutme2#

  • 我想用Ansible检查一个目录是否为空。*

由于没有定义空的意思,如果可能有zero byte files,我理解你的问题,你感兴趣的是文件夹的大小。
根据Use folder size in Conditional

  • 文件夹的stat模块返回的size属性不是告诉你文件夹内容的大小!它只报告目录条目的大小,这可能取决于许多因素,例如目录中包含的文件数量。

如果您要计算文件夹中包含的数据量,可以使用proceed further with the answer thereAnsible: Need generic solution to find size of folder/directory or file
由于这需要使用commandshell,通常不建议在所有情况下使用,因此可以将任务转移到自定义模块中。为此,创建一个用Bash或Shell编写的自定义模块似乎是最好的方法。
下面的概念/示例模块接受一个字符串参数(path)并测试它是一个目录还是文件。之后,它提供了所有文件的目录大小,包括子目录或仅作为结果集的文件大小。

概念/示例模块size.sh

#!/bin/sh

exec 3>&1 4>&2 > /dev/null 2>&1

# Create functions

function return_json() {

    exec 1>&3 2>&4

    jq --null-input --monochrome-output \
        --arg changed "$changed" \
        --arg rc "$rc" \
        --arg stdout "$stdout" \
        --arg stderr "$stderr" \
        --arg directory "$directory" \
        --arg file "$file" \
        --arg msg "$msg" \
       '$ARGS.named'

    exec 3>&1 4>&2 > /dev/null 2>&1

}

# Module helper functions

function dirsize() {

    du -sh "$path" | sort -h

}

function filesize() {

    du -sh "$path"

}

# Module main logic

function module_logic() {

    if [ -f "$path" ]; then
        filesize $path
        file="true"
    elif [ -d "$path" ]; then
        dirsize $path
        directory="true"
    else
        stderr="Cannot access: No such file or directory or Permission denied."
        rc=1
    fi

}

# Set default values

changed="false"
rc=0
stdout=""
stderr=""
directory="false"
file="false"
msg=""

source "$1"

# Check prerequisites

if ! which jq &>/dev/null; then
    exec 1>&3 2>&4
    printf "{ \"changed\": \"$changed\",
           \"rc\": \"1\" ,
           \"stdout\": \"\",
           \"stderr\": \"Command not found: This module require 'jq' installed on the target host. Exiting ...\",
           \"directory\": \"false\" ,
           \"file\": \"false\",
           \"msg\": \"\"}"
    exit 127
fi

if ! grep -q "Red Hat Enterprise Linux" /etc/redhat-release; then
    stderr="Operation not supported: Red Hat Enterprise Linux not found. Exiting ..."
    rc=95

    return_json

    exit $rc

fi

# Validate parameter key and value

if [ -z "$path" ]; then
    stderr="Invalid argument: Parameter path is not provided. Exiting ..."
    rc=22

    return_json

    exit $rc
fi

if [[ $path == *['!:*']* ]]; then
    stderr="Invalid argument: Value path contains invalid characters. Exiting ..."
    rc=22

    return_json

    exit $rc
fi

if [ ${#path} -ge 127 ]; then
    stderr="Argument too long: Value path has too many characters. Exiting ..."
    rc=7

    return_json

    exit $rc
fi

# Main

module_logic $path

changed="false"
msg=$(module_logic $path | sed 's/\t/ /g')

return_json

exit $rc

测试攻略size.yml

---
- hosts: test
  become: false
  gather_facts: false

  tasks:

  - name: Get size behind path
    size:
      path: /root/anaconda-ks.cfg
    register: result
    ignore_errors: true

  - name: Get size behind path
    size:
      path: ''
    register: result
    ignore_errors: true

  - name: Get size behind path
    size:
    register: result
    ignore_errors: true

  - name: Get size behind path
    size:
      path: "/home/{{ ansible_user }}/*"
    register: result
    ignore_errors: true

  - name: Get size behind path
    size:
      path: "/home/{{ ansible_user }}/1111111111/2222222222/3333333333/4444444444/5555555555/6666666666/7777777777/8888888888/9999999999/0000000000/aaaaaaaaaa/bbbbbbbbbb/cccccccccc/"
    register: result
    ignore_errors: true

  - name: Get size behind path
    size:
      path: /home/{{ ansible_user }}
    register: result

  - name: Show result
    debug:
      var: result

结果ansible-playbook --user ${ANSIBLE_USER} size.yml

TASK [Get size behind path] **********************************************
fatal: [test.example.com]: FAILED! => changed=false
  msg: ''
  rc: '1'
  stderr: 'Cannot access: No such file or directory or Permission denied.'
  stderr_lines: <omitted>
  stdout: ''
  stdout_lines: <omitted>
...ignoring

TASK [Get size behind path] **********************************************
fatal: [test.example.com]: FAILED! => changed=false
  msg: ''
  rc: '1'
  stderr: Parameter path is not provided. Exiting ...
  stderr_lines: <omitted>
  stdout: ''
  stdout_lines: <omitted>
...ignoring

TASK [Get size behind path] **********************************************
fatal: [test.example.com]: FAILED! => changed=false
  directory: 'false'
  file: 'false'
  msg: ''
  rc: '22'
  stderr: 'Invalid argument: Value path contains invalid characters. Exiting ...'
  stderr_lines: <omitted>
  stdout: ''
  stdout_lines: <omitted>
...ignoring

TASK [Get size behind path] **********************************************
fatal: [test.example.com]: FAILED! => changed=false
  msg: ''
  rc: '7'
  stderr: Argument 'path' too long. Exiting ...
  stderr_lines: <omitted>
  stdout: ''
  stdout_lines: <omitted>
...ignoring

TASK [Get size behind path] **********************************************
changed: [test.example.com]

TASK [Show result] *******************************************************
ok: [test.example.com] =>
  result:
    changed: 'false'
    failed: false
    msg: 722M /home/user
    rc: '0'
    stderr: ''
    stderr_lines: []
    stdout: ''
    stdout_lines: []

感谢

对于脚本和模块

对于一般Linux和Shell

相关问题