2014-09-22 25 views
6

我正在嘗試將nodev添加到我的/etc/fstab文件中。我在下面使用Ansible命令,但沒有運氣。我的問題在於正則表達式,我不是正則表達式的專家。使用Ansible添加fstab選項

- 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/fstab,我試圖添加nodev的線路是:

/dev/mapper/ex_sys-ex_home /home /ext4 rw,exec,auto,nouser,sync 1 2 
+0

定義「沒有運氣」。實際結果是什麼?我猜測/ etc/fstab沒有改變,而不是爲某些行添加「nodev」? – LarsH 2014-09-22 15:15:48

+0

@LarsH將在第二秒提供結果,我將正則表達式修改爲(^/dev [\ w/_-] + \ s +/[\ w/_-] + \ s +/[\ w/_-] + \ s +((??nodev)[\ w,] +)*)我認爲這可能會起作用 – 2014-09-22 15:18:15

+0

是的,我認爲你在重複組中選擇'\ s +'的事實阻止了匹配。讓我知道如果它不起作用。 – LarsH 2014-09-22 15:22:39

回答

11

雖然這可能不是最優雅的答案,它爲我工作。

- 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 
+0

其實我發現它非常好看和簡潔。 – jojek 2016-04-01 15:00:35

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

受喬的回答的啓發,我製作了這個版本,如果它不在那裏,它將在/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/是一個用於構建和測試這些類型的正則表達式的一個非常有用的工具。只需在那裏啓用「多行」選項並打開「替代」面板,您甚至可以粘貼/etc/fstab並查看您的正則表達式匹配哪條線以及它會對它們做什麼。只要記住在測試時使用實際值而不是Ansible變量{{ point }}