使用Ansible添加fstab选项

问题描述 投票:8回答:6

我正在尝试将nodev添加到我的/etc/fstab文件中。我正在使用下面的Ansible命令,但没有运气。我的问题在于正则表达式,我不是正则表达式的专业人士。

- name: Add nodev to /etc/fstab
  lineinfile:
    dest=/etc/fstab
    backup=yes
    backrefs=yes
    state=present
    regexp='(^/dev[\w/_-]+(\s+(?!nodev)[\w,]+)*)'
    line='\1,nodev'

我试图添加/etc/fstabnodev的其中一条线是:

/dev/mapper/ex_sys-ex_home /home /ext4 rw,exec,auto,nouser,sync 1 2
regex ansible mount mount-point
6个回答
15
投票

虽然这可能不是最优雅的答案,但它对我有用。

- name: Ensure fstab uses nodev
  mount:
    name: "{{ item.mount }}"
    src: "{{ item.device }}"
    fstype: "{{ item.fstype }}"
    opts: "{{ item.options }},nodev"
    state: present
  with_items: ansible_mounts
  when: item.options.find(",") >= 0 and item.options.find("nodev") == -1

3
投票

受Joe的回答启发,我制作了这个版本,如果它已经存在,它将在/etc/fstab的特定行添加一个选项。这也将保留该线已有的任何其他选项。

main.yml

- import_tasks: fstab-opt-present.yml point=/home opt=nodev

fstab中-OPT-present.yml

- name: '/etc/fstab: Set opt "{{ opt }}" for mount point {{ point }}'
  lineinfile:
    path: /etc/fstab
    backup: yes
    backrefs: yes
    regexp: '^(\S+\s+{{ point }}\s+\S+\s+)(?!(?:\S*,)?{{ opt }}(?:,\S*)?\s+)(\S+)(\s+.+)$'
    line: '\1{{ opt }},\2\3'
  register: fstab

- name: 'If {{ point }} changed, remount'
  command: 'mount {{ point }} -o remount'
  when: fstab.changed

https://regex101.com/是一个非常有用的工具,用于构建和测试这些regexp。只需在那里启用“多行”选项并打开“替换”面板,您甚至可以粘贴到/etc/fstab中,看看你的正则表达式将匹配哪些行以及它们将对它们做什么。只需记住在那里测试时使用真值而不是Ansible变量{{ point }}


2
投票

我们开发了第三方ansible模块来添加,设置或删除挂载选项。看看这个!

  - mountopts:
      name: /
      option: nodev

https://github.com/Uberspace/ansible-mountopts


0
投票

登陆这里寻找答案,最后为我的用例滚动:

main.yml

- include: fstab-opts.yml point=/tmp opts=noexec,nodev,nosuid,noatime
- include: fstab-opts.yml point=/backup opts=noatime

fstab中,opts.yml

---

- name: 'Ensure {{ point }} flags'
  lineinfile:
    path: /etc/fstab
    # uses "(not-spaces spaces /tmp spaces )(not-spaces)(the rest)" pattern to match column content and capture args
    regexp: '^([^ ]+[ ]+\{{ point }}[ ]+[^ ]+[ ]+)([^ ]+)(.*)'
    line: '\1{{ opts }}\3'
    backrefs: yes
  register: fstab

- name: 'If {{ point }} changed, remount'
  command: mount -o remount {{ point }}
  when: fstab.changed

0
投票

测试和工作正常

  • name:set nodev option replace:path:/ etc / fstab backup:yes regexp:'^(\ S + \ s +)(/ \ S +)(\ s +)((?:ext4 | xfs)\ s +)(?!( ?:\ S *,)?nodev(?:,\ S *)?\ s +)(\ S +)(\ s +。+)$'replace:'\ 1 \ 2 \ 4 \ 5,nodev \ 6'

它不包括将nodev添加到/(root),仅设置为ext4和xfs文件系统。不添加到临时文件系统。

注意:在测试regexp101时,请确保选择python


0
投票

我想声明似乎有一个新的ansible模块,它更容易涵盖所有这些:https://docs.ansible.com/ansible/latest/modules/mount_module.html

© www.soinside.com 2019 - 2024. All rights reserved.