ansible 常用模块 shell

shell 模块说明

shell 模块用于在目标主机上执行命令,类似于在命令行中直接输入命令。这个模块允许你执行任何命令,但是要注意命令的安全性和可重复性。

shell 模块语法

- name: Execute shell command
  ansible.builtin.shell:
    cmd: <command>
    chdir: <directory>     # 可选,指定命令的工作目录
    creates: <file>        # 可选,如果文件存在,则不执行命令
    removes: <file>        # 可选,如果文件不存在,则执行命令
    warn: <yes|no>         # 可选,默认为 yes,当命令返回非零退出代码时是否给出警告
  register: <result_variable>  # 可选,用于存储命令执行结果的变量名

shell 模块参数说明

cmd: 要执行的命令。可以是单个命令,也可以是多个命令以及管道、重定向等复杂的命令。
chdir: 可选参数,指定命令执行时的工作目录。
creates: 可选参数,如果指定的文件已经存在,则不执行命令。
removes: 可选参数,如果指定的文件不存在,则执行命令。
warn: 可选参数,默认为 yes,当命令返回非零退出代码时是否给出警告。
register: 可选参数,用于存储命令执行结果的变量名。

shell 模块示例

简单的执行命令

- name: Run a shell command
  ansible.builtin.shell:
    cmd: ls -l

使用变量和管道执行命令

- name: Use variables and pipes in shell command
  ansible.builtin.shell:
    cmd: cat /var/log/messages | grep error

指定工作目录执行命令

- name: Execute command in a specific directory
  ansible.builtin.shell:
    cmd: ./run_script.sh
    chdir: /path/to/script/directory

检查文件是否存在后执行命令

- name: Only run command if file does not exist
  ansible.builtin.shell:
    cmd: create_file.sh
    creates: /path/to/file

检查文件是否不存在后执行命令

- name: Run command if file does not exist
  ansible.builtin.shell:
    cmd: remove_file.sh
    removes: /path/to/file

忽略命令返回的非零退出代码

- name: Run a command and ignore non-zero return code
  ansible.builtin.shell:
    cmd: command_that_may_fail.sh
    warn: no
    

使用 register 存储命令执行结果 

- name: Get users with /bin/bash shell excluding specified users
    ansible.builtin.shell:
      cmd: |
        getent passwd | awk -F: '$NF=="/bin/bash" {print $1}'
    register: bash_users
    changed_when: false

- name: Set password expiry for users with /bin/bash shell
    command: chage -M 90 {{ item }}
    with_items: "{{ bash_users.stdout_lines }}"
    register: change_users

参考文档

https://docs.ansible.com/ansible/latest/collections/ansible/builtin/shell_module.html#ansible-collections-ansible-builtin-shell-module

posted @ 2024-04-30 09:01  小吉猫  阅读(140)  评论(0编辑  收藏  举报