ansible 文件操作 lineinfile & blockinfile (一)

有時(shí)需要批量修改文件,比如 /etc/rc.local 等, 可以使用blockinfile 或者 lineinfile

blockinfile

blockinfile 會在文件中插入一段內(nèi)容,插入時(shí)會根據(jù)marker 寫入/更新到指定的塊中,可以指定需要插入的位置
關(guān)鍵參數(shù):

  1. path/dest/destfile/name :指定需要修改的文件
  2. block/content: 需要添加/修改的內(nèi)容
  3. marker:標(biāo)記內(nèi)容,默認(rèn)# BEGIN ANSIBLE MANAGED BLOCK ,例如:#{mark} test for fun , mark 會被替換為 BEGIN/END
  4. insertafter:插入指定內(nèi)容之后霉祸, 默認(rèn)插入到結(jié)尾
  5. insertbefore: 插入指定內(nèi)容之前

注意:

  1. 如果marker 相同會更新內(nèi)容,如果多次寫入,注意區(qū)分marker
  2. 如果指定了marker牺六,insertbefore/after 會不生效,仍修改該標(biāo)記中的內(nèi)容

ansible-doc blockinfile:

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

        This module will insert/update/remove a block of multi-line text surrounded by customizable marker lines.

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

- 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

- block
        The text to insert inside the marker lines. If it's missing or an empty string, the block will be removed as if `state'
        were specified to `absent'.
        (Aliases: content)[Default: ]

- create
        Create a new file if it doesn't exist.
        [Default: no]
        type: bool

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

- insertafter
        If specified, the block will be inserted after the last match of specified regular expression. A special value is
        available; `EOF' for inserting the block at the end of the file.  If specified regular expression has no matches, `EOF'
        will be used instead.
        (Choices: EOF, *regex*)[Default: EOF]

- insertbefore
        If specified, the block will be inserted before the last match of specified regular expression. A special value is
        available; `BOF' for inserting the block at the beginning of the file.  If specified regular expression has no matches,
        the block will be inserted at the end of the file.
        (Choices: BOF, *regex*)[Default: (null)]

- marker
        The marker line template. "{mark}" will be replaced with the values in marker_begin (default="BEGIN") and marker_end
        (default="END").
        [Default: # {mark} ANSIBLE MANAGED BLOCK]

- marker_begin
        This will be inserted at {mark} in the opening ansible block marker.
        [Default: BEGIN]
        version_added: 2.5

- marker_end
        This will be inserted at {mark} in the closing ansible block marker.
        [Default: END]
        version_added: 2.5

- 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]

- 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)

- 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 block 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:
      * This module supports check mode.
      * When using 'with_*' loops be aware that if you do not set a unique mark the block will be overwritten on each
        iteration.
      * As of Ansible 2.3, the `dest' option has been changed to `path' as default, but `dest' still works as well.
      * Option `follow' has been removed in version 2.5, because this module modifies the contents of the file so
        `follow=no' doesn't make sense.

AUTHOR: YAEGASHI Takeshi (@yaegashi)
        METADATA:
          status:
          - preview
          supported_by: core

例子

EXAMPLES:
# Before 2.3, option 'dest' or 'name' was used instead of 'path'
- name: insert/update "Match User" configuration block in /etc/ssh/sshd_config
  blockinfile:
    path: /etc/ssh/sshd_config
    block: |
      Match User ansible-agent
      PasswordAuthentication no

- name: insert/update eth0 configuration stanza in /etc/network/interfaces
        (it might be better to copy files into /etc/network/interfaces.d/)
  blockinfile:
    path: /etc/network/interfaces
    block: |
      iface eth0 inet static
          address 192.0.2.23
          netmask 255.255.255.0

- name: insert/update configuration using a local file and validate it
  blockinfile:
    block: "{{ lookup('file', './local/ssh_config') }}"
    dest: "/etc/ssh/ssh_config"
    backup: yes
    validate: "/usr/sbin/sshd -T -f %s"

- name: insert/update HTML surrounded by custom markers after <body> line
  blockinfile:
    path: /var/www/html/index.html
    marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
    insertafter: "<body>"
    content: |
      <h1>Welcome to {{ ansible_hostname }}</h1>
      <p>Last updated on {{ ansible_date_time.iso8601 }}</p>

- name: remove HTML as well as surrounding markers
  blockinfile:
    path: /var/www/html/index.html
    marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
    content: ""

- name: Add mappings to /etc/hosts
  blockinfile:
    path: /etc/hosts
    block: |
      {{ item.ip }} {{ item.name }}
    marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"
  with_items:
    - { name: host1, ip: 10.10.1.10 }
    - { name: host2, ip: 10.10.1.11 }
    - { name: host3, ip: 10.10.1.12 }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末汗捡,一起剝皮案震驚了整個(gè)濱河市淑际,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌扇住,老刑警劉巖春缕,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異艘蹋,居然都是意外死亡锄贼,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進(jìn)店門女阀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來宅荤,“玉大人屑迂,你說我怎么就攤上這事》爰” “怎么了惹盼?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長惫确。 經(jīng)常有香客問我手报,道長,這世上最難降的妖魔是什么改化? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任掩蛤,我火速辦了婚禮,結(jié)果婚禮上所袁,老公的妹妹穿的比我還像新娘盏档。我一直安慰自己,他們只是感情好燥爷,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布蜈亩。 她就那樣靜靜地躺著,像睡著了一般前翎。 火紅的嫁衣襯著肌膚如雪稚配。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天港华,我揣著相機(jī)與錄音道川,去河邊找鬼。 笑死立宜,一個(gè)胖子當(dāng)著我的面吹牛冒萄,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播橙数,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼尊流,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了灯帮?” 一聲冷哼從身側(cè)響起崖技,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎钟哥,沒想到半個(gè)月后迎献,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡腻贰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年吁恍,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,503評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡践盼,死狀恐怖鸦采,靈堂內(nèi)的尸體忽然破棺而出宾巍,到底是詐尸還是另有隱情咕幻,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布顶霞,位于F島的核電站肄程,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏选浑。R本人自食惡果不足惜蓝厌,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望古徒。 院中可真熱鬧拓提,春花似錦、人聲如沸隧膘。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽疹吃。三九已至蹦疑,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間萨驶,已是汗流浹背歉摧。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留腔呜,地道東北人叁温。 一個(gè)月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像核畴,于是被迫代替她去往敵國和親膝但。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評論 2 359