ansible 文件操作 lineinfile & blockinfile (二)

lineinfile

用来确定文件中的特定行存在,或者进行修改。用来修改单独一行时很有用,可以使用python正则表达式,例如对配置文件进行修改。如果想修改多行可以考虑replace,或者考虑blockinfile 如果想添加/更新一段内容。

自己用的不多,记下来避免忘了😊

主要参数:

  1. path: 文件位置 (Aliases: dest, destfile, name)
  2. line:想要插入或替换的行
  3. regexp: 正则表达式。使用该表达式去搜索行,只有最后一行会被修改

ansible-doc lineinfile:

> LINEINFILE    (/usr/lib/python2.7/site-packages/ansible/modules/files/lineinfile.py)

        This module ensures a particular line is in a file, or replace an existing line using a back-referenced regular expression. This
        is primarily useful when you want to change a single line in a file only. See the [replace] module if you want to change
        multiple, similar lines or check [blockinfile] if you want to insert/update/remove a block of lines in a file. For other cases,
        see the [copy] or [template] modules.

OPTIONS (= is mandatory):

- attributes
        Attributes the file or directory should have. To get supported flags look at the man page for `chattr' on the target system. This
        string should contain the attributes in the same order as the one displayed by `lsattr'.
        (Aliases: attr)[Default: None]
        version_added: 2.3

- backrefs
        Used with `state=present'. If set, line can contain backreferences (both positional and named) that will get populated if the
        `regexp' matches. This flag changes the operation of the module slightly; `insertbefore' and `insertafter' will be ignored, and
        if the `regexp' doesn't match anywhere in the file, the file will be left unchanged. If the `regexp' does match, the last
        matching line will be replaced by the expanded line parameter.
        [Default: no]
        type: bool
        version_added: 1.1

- backup
        Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it
        incorrectly.
        [Default: no]
        type: bool

- create
        Used with `state=present'. If specified, the file will be created if it does not already exist. By default it will fail if the
        file is missing.
        [Default: no]
        type: bool

- firstmatch
        Used with `insertafter' or `insertbefore'. If set, `insertafter' and `inserbefore' find a first line has regular expression
        matches.
        [Default: no]
        type: bool
        version_added: 2.5

- group
        Name of the group that should own the file/directory, as would be fed to `chown'.
        [Default: None]

- insertafter
        Used with `state=present'. If specified, the line will be inserted after the last match of specified regular expression. If the
        first match is required, use(firstmatch=yes). A special value is available; `EOF' for inserting the line at the end of the file.
        If specified regular expression has no matches, EOF will be used instead. May not be used with `backrefs'.
        (Choices: EOF, *regex*)[Default: EOF]

- insertbefore
        Used with `state=present'. If specified, the line will be inserted before the last match of specified regular expression. If the
        first match is required, use(firstmatch=yes). A value is available; `BOF' for inserting the line at the beginning of the file. If
        specified regular expression has no matches, the line will be inserted at the end of the file.  May not be used with `backrefs'.
        (Choices: BOF, *regex*)[Default: (null)]
        version_added: 1.1

- line
        Required for `state=present'. The line to insert/replace into the file. If `backrefs' is set, may contain backreferences that
        will get expanded with the `regexp' capture groups if the regexp matches.
        [Default: (null)]

- mode
        Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers (like
        `0644' or `01777'). Leaving off the leading zero will likely have unexpected results. As of version 1.8, the mode may be
        specified as a symbolic mode (for example, `u+rwx' or `u=rw,g=r,o=r').
        [Default: None]

- others
        All arguments accepted by the [file] module also work here.
        [Default: (null)]

- owner
        Name of the user that should own the file/directory, as would be fed to `chown'.
        [Default: None]

= path
        The file to modify.
        Before 2.3 this option was only usable as `dest', `destfile' and `name'.
        (Aliases: dest, destfile, name)

- regexp
        The regular expression to look for in every line of the file. For `state=present', the pattern to replace if found. Only the last
        line found will be replaced. For `state=absent', the pattern of the line(s) to remove. Uses Python regular expressions. See
        http://docs.python.org/2/library/re.html.
        [Default: (null)]
        version_added: 1.7

- selevel
        Level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works
        as for `seuser'.
        [Default: s0]

- serole
        Role part of SELinux file context, `_default' feature works as for `seuser'.
        [Default: None]

- setype
        Type part of SELinux file context, `_default' feature works as for `seuser'.
        [Default: None]

- seuser
        User part of SELinux file context. Will default to system policy, if applicable. If set to `_default', it will use the `user'
        portion of the policy if available.
        [Default: None]

- state
        Whether the line should be there or not.
        (Choices: absent, present)[Default: present]

- unsafe_writes
        Normally this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, sometimes
        systems are configured or just broken in ways that prevent this. One example are docker mounted files, they cannot be updated
        atomically and can only be done in an unsafe manner.
        This boolean option allows ansible to fall back to unsafe methods of updating files for those cases in which you do not have any
        other choice. Be aware that this is subject to race conditions and can lead to data corruption.
        [Default: False]
        type: bool
        version_added: 2.2

- validate
        The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be
        present as in the example below. The command is passed securely so shell features like expansion and pipes won't work.
        [Default: None]


NOTES:
      * As of Ansible 2.3, the `dest' option has been changed to `path' as default, but `dest' still works as well.

AUTHOR: Daniel Hokka Zakrissoni (@dhozac), Ahti Kitsik (@ahtik)
        METADATA:
          status:
          - preview
          supported_by: core

EXAMPLES:

# Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- lineinfile:
    path: /etc/selinux/config
    regexp: '^SELINUX='
    line: 'SELINUX=enforcing'

- lineinfile:
    path: /etc/sudoers
    state: absent
    regexp: '^%wheel'

- lineinfile:
    path: /etc/hosts
    regexp: '^127\.0\.0\.1'
    line: '127.0.0.1 localhost'
    owner: root
    group: root
    mode: 0644

- lineinfile:
    path: /etc/httpd/conf/httpd.conf
    regexp: '^Listen '
    insertafter: '^#Listen '
    line: 'Listen 8080'

- lineinfile:
    path: /etc/services
    regexp: '^# port for http'
    insertbefore: '^www.*80/tcp'
    line: '# port for http by default'

# Add a line to a file if it does not exist, without passing regexp
- lineinfile:
    path: /tmp/testfile
    line: '192.168.1.99 foo.lab.net foo'

# Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs.
- lineinfile:
    path: /etc/sudoers
    state: present
    regexp: '^%wheel\s'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'

# Yaml requires escaping backslashes in double quotes but not in single quotes
- lineinfile:
    path: /opt/jboss-as/bin/standalone.conf
    regexp: '^(.*)Xms(\\d+)m(.*)$'
    line: '\1Xms${xms}m\3'
    backrefs: yes

# Validate the sudoers file before saving
- lineinfile:
    path: /etc/sudoers
    state: present
    regexp: '^%ADMIN ALL='
    line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'
    validate: '/usr/sbin/visudo -cf %s'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,980评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,178评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,868评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,498评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,492评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,521评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,910评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,569评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,793评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,559评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,639评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,342评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,931评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,904评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,144评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,833评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,350评论 2 342