1. Ansible Modules: Command vs Shell

在 Linux 目标主机上执行命令时,command 和 shell 模块常常被混淆,但它们在功能上有所不同。

  • command
    • 功能:在目标主机上执行命令,绕过 shell。
    • 特点:不会受本地 shell 变量影响,无法执行 shell 内置功能(如重定向、变量展开等)。
    • 适用场景:执行简单的二进制命令。
    • 返回值:始终将 changed 设置为 True。
  • shell
    • 功能:在目标主机上执行 shell 命令,支持重定向和 shell 内置功能。
    • 特点:可以执行复杂的命令组合(如管道、&&、;)。
    • 适用场景:需要使用 shell 功能时(如变量展开、文件操作)。
    • 返回值:始终将 changed 设置为 True。

建议:尽可能使用专门的 Ansible 模块,而不是 command 或 shell。如果必须使用,优先选择 command,因为它更安全且结果更可预测。

2. Ansible 模块:ping

ansible.builtin.ping 模块用于测试 Ansible 是否能够登录到目标主机,并确认主机上是否有可用的 Python 解释器。

  • 参数:
    • data(字符串):默认返回值为 pong,可通过此参数自定义返回值。
    • ping(字符串):默认返回值为 pong。

示例:

---
- name: ping module demo
  hosts: all
  tasks:
    - name: test connection
      ansible.builtin.ping:

3. Ansible 模块:debug

ansible.builtin.debug 模块用于在执行过程中打印消息或变量。

  • 参数:
    • msg(字符串):自定义消息。
    • var(字符串):打印变量值。
    • verbosity(整数):控制消息的显示级别(0-3)。

示例:

---
- name: debug module demo
  hosts: all
  vars:
    fruit: "apple"
  tasks:
    - name: debug message
      ansible.builtin.debug:
        msg: "our fruit is {{ fruit }}"
        verbosity: 2

4. Ansible 模块:lineinfile

ansible.builtin.lineinfile 模块用于在文件中插入、更新或删除单行文本。

  • 参数:
    • path(字符串):文件路径。
    • line(字符串):要插入的文本。
    • insertafter/insertbefore(字符串):指定插入位置。
    • validate(字符串):验证命令。
    • create(布尔值):如果文件不存在则创建。
    • state(字符串):present 或 absent。

示例:

---
- name: lineinfile module demo
  hosts: all
  become: true
  tasks:
    - name: allow password authentication
      ansible.builtin.lineinfile:
        state: present
        dest: /etc/ssh/sshd_config
        regexp: "^PasswordAuthentication"
        line: "PasswordAuthentication yes"
        validate: 'sshd -t -f %s'

5. Ansible 模块:blockinfile

ansible.builtin.blockinfile 模块用于在文件中插入、更新或删除多行文本块。

  • 参数:
    • path(字符串):文件路径。
    • block(字符串):要插入的文本块。
    • insertafter/insertbefore(字符串):指定插入位置。
    • validate(字符串):验证命令。
    • create(布尔值):如果文件不存在则创建。
    • state(字符串):present 或 absent。
    • marker_begin/marker_end(字符串):自定义标记。

示例:

---
- name: blockinfile module demo
  hosts: all
  become: true
  tasks:
    - name: Generate /etc/hosts file
      ansible.builtin.blockinfile:
        state: present
        dest: /etc/hosts
        content: |
          192.168.0.200 demo demo.example.com

6. Ansible 模块:slurp

ansible.builtin.slurp 模块用于从远程主机读取文件内容,并以 Base64 编码返回。

  • 参数:
    • src(字符串):远程文件路径。

示例:

---
- name: slurp module demo
  hosts: all
  become: false
  vars:
    remotefile: "/proc/cpuinfo"
  tasks:
    - name: slurp remote file
      ansible.builtin.slurp:
        src: "{{ remotefile }}"
      register: slurpfile

    - name: print remote file
      ansible.builtin.debug:
        msg: "{{ slurpfile['content'] | b64decode }}"

7. Ansible 模块:cron

ansible.builtin.cron 模块用于管理远程主机上的 cron 任务。

  • 参数:
    • name(字符串):任务描述。
    • state(字符串):present 或 absent。
    • job(字符串):要执行的命令。
    • user(字符串):指定用户,默认为当前用户。
    • minute/hour/day/month/weekday(字符串):任务执行时间。
    • special_time(字符串):预定义的时间间隔(如 hourly、daily、weekly)。
    • cron_file(字符串):指定 cron 文件名。

示例:

---
- name: cron module demo
  hosts: all
  tasks:
    - name: "example cronjob"
      ansible.builtin.cron:
        name: "test"
        state: present
        minute: "*/2"
        hour: "*"
        day: "*"
        month: "*"
        weekday: "*"
        job: 'logger "ansible-pilot"'

8. Ansible 模块:template

ansible.builtin.template 模块用于将模板文件渲染到目标主机。

  • 参数:
    • src(路径):模板文件路径。
    • dest(路径):目标路径。
    • validate(字符串):验证命令。
    • backup(布尔值):是否创建备份文件。
    • mode/owner/group:文件权限。
    • setype/seuser/selevel:SELinux 属性。

示例:

---
- name: template module demo
  hosts: all
  become: true
  vars:
    page_title: "Placeholder"
    page_description: |
      This is my placeholder page example.
      Multiline is possible ;-)
  tasks:
    - name: install Nginx
      ansible.builtin.apt:
        name: nginx
        state: latest

    - name: apply page template
      ansible.builtin.template:
        src: templates/placeholder.html.j2
        dest: /var/www/html/index.html

模板文件(templates/placeholder.html.j2):

<html>
<head>
  <title>{{ page_title }}</title>
</head>
<body>
  <h1>{{ page_title }}</h1>
  <p>{{ page_description }}</p>
</body>
</html>

9. Ansible 模块:copy

ansible.builtin.copy 模块用于将文件从控制节点复制到远程主机。

  • 参数:
    • dest(路径):目标路径。
    • src(路径):源文件路径。
    • backup(布尔值):是否创建备份文件。
    • validate(字符串):验证命令。
    • mode/owner/group:文件权限。
    • setype/seuser/selevel:SELinux 属性。

示例:

---
- name: copy module demo
  hosts: all
  tasks:
    - name: copy report.txt
      ansible.builtin.copy:
        src: report.txt
        dest: /home/devops/report.txt
        owner: devops
        mode: '0644'

10. Ansible 模块:fetch

ansible.builtin.fetch 模块用于从远程主机获取文件。

  • 参数:
    • src(路径):远程文件路径。
    • dest(路径):本地保存路径。
    • fail_on_missing(布尔值):如果文件不存在是否失败。
    • validate_checksum(布尔值):是否验证文件校验和。
    • flat(布尔值):是否使用扁平化路径。

示例:

---
- name: fetch module demo
  hosts: all
  become: true
  vars:
    log_file: "/var/log/messages"
    dump_dir: "logs"
  tasks:
    - name: fetch log
      ansible.builtin.fetch:
        src: "{{ log_file }}"
        dest: "{{ dump_dir }}"

11. Ansible 模块:service_facts 和 service

ansible.builtin.service_facts 和 ansible.builtin.service 模块用于管理远程主机上的服务。

  • 参数:
    • name(字符串):服务名称。
    • state(字符串):started、stopped、restarted、reloaded。
    • enabled(布尔值):是否开机启动。
    • arguments/args(字符串):额外参数。

示例:

---
- name: service module demo
  hosts: all
  become: true
  vars:
    services_on_boot:
      - "chronyd.service"
  tasks:
    - name: populate service facts
      ansible.builtin.service_facts:

    - name: enable services on boot
      ansible.builtin.service:
        name: "{{ item }}"
        enabled: true
        state: started
      when: "item in services"
      with_items: '{{ services_on_boot }}'

12. Ansible 模块:env

ansible.builtin.env 模块用于读取环境变量。

  • 参数:
    • _terms(字符串):环境变量名称。

示例:

---
- name: environment demo
  hosts: all
  tasks:
    - name: display HOME
      ansible.builtin.debug:
        msg: "{{ lookup('env', 'HOME') }}"

13. Ansible 模块:lineinfile

ansible.builtin.lineinfile 模块用于在文件中插入、更新或删除单行文本。

  • 参数:
    • path(路径):文件路径。
    • line(字符串):要插入的文本。
    • regexp(字符串):正则表达式,用于匹配现有行。
    • state(字符串):present 或 absent。

示例:

---
- name: set environment demo
  hosts: all
  gather_facts: false
  become: true
  vars:
    os_environment:
      - key: EDITOR
        value: vi
      - key: MY_ENV_VARIABLE
        value: ansiblepilot
  tasks:
    - name: customize /etc/environment
      ansible.builtin.lineinfile:
        dest: "/etc/environment"
        state: present
        regexp: "^{{ item.key }}="
        line: "{{ item.key }}={{ item.value }}"
      with_items: "{{ os_environment }}"

14. Ansible 模块:copy vs template

ansible.builtin.copy 和 ansible.builtin.template 模块都可以将变量写入文件,但 template 模块更适合复杂的格式化和变量处理。

示例:

  • 使用 copy 模块:

    ```yaml

    • name: copy module demo hosts: all vars: fruit: "banana" output: "output.txt" tasks:
      • name: write to file ansible.builtin.copy: content: "{{ fruit }}" dest: "{{ output }}" ```
  • 使用 template 模块:

    ```yaml

    • name: template module demo hosts: all vars: fruit: "apple" output: "output.txt" tasks:
      • name: write to file ansible.builtin.template: src: "mytemplate.j2" dest: "{{ output }}" ```

    模板文件(mytemplate.j2):

    jinja2 {{ fruit }}

总结

Ansible 提供了丰富的模块来自动化 Linux 系统管理任务。通过合理选择模块和参数,可以高效地完成各种任务,从简单的文件操作到复杂的系统配置。