Ansible blockinfile examples

Ansible blockinfile examples DEFAULT

If you are not familiar with modules, check out Ansible - Getting Started with Modules.

There are a few different modules that can be used to modify a file.

  • The blockinfile module can be used to append, change, or remove a block of lines in a file. 
  • The lineinfile module can be used to append, change, or remove a line in a file. 
  • The replace module can be used to change or remove a line in a file.

AVOID TROUBLE

If the target file does not exist, invoking this playbook will return an error like the sample below.

For this reason, you will almost always want to use the create: true parameter, so that the file is created if it does not exist. Or use the stat module to determine if the file exists, and then used the when parameter to only execute the task when the file exists.

 

At the bare minimum, the following is all that is needed to invoke this module. By default, the block is appended as a new line at the end of the file (EOF).

 

When the target file does not exist, invoking this playbook will return an error. For this reason, you probably want to first use the stat module to determine if the target file exists, and then use the file module to create the target file, or use the when parameter to skip the lineinfile module if the target file does not exist. Or, you could use the ignore_errors parameter.

 

If the target file exists, and the file was successfully updated, the folllowing should be displayed.

 

foo.txt should now contain the following.

 


marker

Notice that # BEGIN ANSBILE MANAGED BLOCK and # END ANSIBLE MANAGED BLOCK were appended to foo.txt. These are the default marker lines. The following will produce the same exact result as above.

 

You can create your own marker. 

 

When the block parameter is empty, the marker lines and everything inside the marker lines will be removed. Notice the marker parameter is not used here. When the default marker lines are being used, the marker parameter is not needed to remove everything inside the marker lines.

 

Or, when the state parameter is absent, everything inside the marker lines will be removed.

 

If you have custom marker lines, then the marker parameter will need to be included.

 


Optional Parameters

The blockinfile module accepts the following parameters.

  • group (e.g. group: "wheel")
  • mode (e.g. mode: "2775")
  • owner (e.g. owner: "root")
  • seuser - SELinux user (e.g. seuser: "unconfined_u")
  • serole - SELinux role (e.g. serole: "object_r")
  • setype - SELinux type (e.g. setype: "httpd_sys_content_t")
  • selevel - SELinux level (e.g. selevel: "s0")
  • validate - Validate file

 

Here is an example of how these parameters would be used.

 

Sours: http://www.freekb.net/Article?id=2451

ansible.builtin.blockinfile – Insert/update/remove a text block surrounded by marker lines

ParameterChoices/DefaultsCommentsattributes

string

added in 2.3 of ansible.builtin

The attributes the resulting 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.

The operator is assumed as default, otherwise or operators need to be included in the string.


aliases: attr

backup

boolean

    Choices:
  • no ←

  • yes

Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.

block

string

Default:

""

The text to insert inside the marker lines.

If it is missing or an empty string, the block will be removed as if were specified to .


aliases: content

create

boolean

    Choices:
  • no ←

  • yes

Create a new file if it does not exist.

group

string

Name of the group that should own the file/directory, as would be fed to chown.

insertafter

string

    Choices:
  • EOF ←

  • *regex*

If specified and no begin/ending lines are found, the block will be inserted after the last match of specified regular expression.

A special value is available; for inserting the block at the end of the file.

If specified regular expression has no matches, will be used instead.

insertbefore

string

If specified and no begin/ending lines are found, the block will be inserted before the last match of specified regular expression.

A special value is available; 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.

marker

string

Default:

"# {mark} ANSIBLE MANAGED BLOCK"

The marker line template.

will be replaced with the values in (default="BEGIN") and (default="END").

Using a custom marker without the variable may result in the block being repeatedly inserted on subsequent playbook runs.

marker_begin

string

added in 2.5 of ansible.builtin

Default:

"BEGIN"

This will be inserted at in the opening ansible block marker.

marker_end

string

added in 2.5 of ansible.builtin

Default:

"END"

This will be inserted at in the closing ansible block marker.

mode

raw

The permissions the resulting file or directory should have.

For those used to /usr/bin/chmod remember that modes are actually octal numbers. You must either add a leading zero so that Ansible's YAML parser knows it is an octal number (like or ) or quote it (like or ) so Ansible receives a string and can do its own conversion from string into number.

Giving Ansible a number without following one of these rules will end up with a decimal number which will have unexpected results.

As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, or ).

If is not specified and the destination file does not exist, the default on the system will be used when setting the mode for the newly created file.

If is not specified and the destination file does exist, the mode of the existing file will be used.

Specifying is the best way to ensure files are created with the correct permissions. See CVE-2020-1736 for further details.

owner

string

Name of the user that should own the file/directory, as would be fed to chown.

path

path / required

The file to modify.

Before Ansible 2.3 this option was only usable as dest, destfile and name.


aliases: dest, destfile, name

selevel

string

The level part of the SELinux file context.

This is the MLS/MCS attribute, sometimes known as the .

When set to , it will use the portion of the policy if available.

serole

string

The role part of the SELinux file context.

When set to , it will use the portion of the policy if available.

setype

string

The type part of the SELinux file context.

When set to , it will use the portion of the policy if available.

seuser

string

The user part of the SELinux file context.

By default it uses the policy, where applicable.

When set to , it will use the portion of the policy if available.

state

string

    Choices:
  • absent
  • present ←

Whether the block should be there or not.

unsafe_writes

boolean

added in 2.2 of ansible.builtin

    Choices:
  • no ←

  • yes

Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target file.

By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted files, which cannot be updated atomically from inside the container and can only be written in an unsafe manner.

This option allows Ansible to fall back to unsafe methods of updating files when atomic operations fail (however, it doesn't force Ansible to perform unsafe writes).

IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.

validate

string

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 examples below.

The command is passed securely so shell features like expansion and pipes will not work.

Sours: https://docs.ansible.com/ansible/latest/collections/ansible/builtin/blockinfile_module.html
  1. Saitama emoji
  2. Chillicothe mo radar
  3. Ameer hussain
  4. Blank teddy bears

Ansible Blockinfile Examples

Ansible blockinfile module is used to insert/update/remove a block of lines in a file. This module will insert/update/remove a block of multi-line text surrounded by customizable marker lines. in this blog post i will show you list of examples to insert/update/remove  lines from a file using ansible blockinfile module.

Inserting a Block of Lines using ansible blockinfile:

in this example i am going to show you how to add block of lines to a file using ansible blockinfile module. Here i have text file called abc.txt. and in this file i written some names.

[rootmaniprabu-172-31-22-205 ~]# cat abc.txt Liam Noah William James Oliver Benjamin Elijah Lucas

now by using ansible blockinfile module i will add some lines to this file.

[rootmaniprabu-172-31-22-205 ~]# cat blockinfile.yml --- - hosts: localhost gather_facts: no tasks: - name: add block of lines to a file. blockinfile: path: /root/abc.txt block: | Hi this is decoding devops Check out my blog for all devops tools backup: yes

along with blockinfile module we use some extra arguments to add block of lines to a file those are path,block,backup.

path: here we have to give the path of the file which you want to modify.

block: here you have to write your lines of code(content) which you want to add to the file

backup: if you mention backup yes, it will create one file in the current directory with timestamp. it will have the content of your old file. in this way we can take backup of your file.

By default, the block will be inserted at the end of the file.

output:

[rootmaniprabu-172-31-22-205 ~]# ansible-playbook blockinfile.yml [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' PLAY [localhost] *********************************************************************************************************************************************************** TASK [add block of lines to a file.] *************************************************************************************************************************************** changed: [localhost] PLAY RECAP ***************************************************************************************************************************************************************** localhost : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [rootmaniprabu-172-31-22-205 ~]# cat abc.txt Liam Noah William James Oliver Benjamin Elijah Lucas # BEGIN ANSIBLE MANAGED BLOCK Hi this is decoding devops Check out my blog for all devops tools # END ANSIBLE MANAGED BLOCK [rootmaniprabu-172-31-22-205 ~]# ls abc.txt abc.txt.8576.2019-07-09Tuấn Nguyễn Anh:22:38~ blockinfile.yml [rootmaniprabu-172-31-22-205 ~]#

Here you can see in the file  after Lucas new lines are added and you can see one backup file  abc.txt.8576.2019-07-09Tuấn Nguyễn Anh:22:38~ is created.

Sours: https://www.decodingdevops.com/ansible-blockinfile-examples/
Edit multi-line text - Ansible module blockinfile

Ansible Role: blockinfile

This role contains no tasks, but provides blockinfile module which might be useful when you want to maintain multi-line snippets in config files in /etc.

Ansible Galaxy Page: https://galaxy.ansible.com/list#/roles/1475

Request for review:The pull request to ansible-modules-extras has been made to include blockinfile module in the official distribution of Ansible, which enables you to use blockinfile as a standard module without this role!

If you use this module and feel it's useful, please leave some endorsement comments on the PR. I greatly appreciate if you're an eligible reviewer (existing module author) and could take some time to review the PR, otherwise if you could ask reviewers of your acquiaintance for the review. It needs two +1 votes from reviewers in order to be nominated for inclusion.

blockinfile Module

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

Example task:

- blockinfile: dest: /etc/network/interfacesblock: | iface eth0 inet static address 192.168.0.1 netmask 255.255.255.0

Text inserted/updated by the task in /etc/network/interfaces:

It uses marker lines as default. You can specify alternative marker lines by option when you need to update files in other formats like HTML, or run multiple blockinfile tasks on the same file.

Options

If this section doesn't show nicely in Ansible Galaxy Page, please refer to equivalent in GitHub Page.

parameterrequireddefaultchoicescomments
backup
nono

Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.

block
no

The text to insert inside the marker lines. If it's missing or an empty string, the block will be removed as if were specified to .


aliases: content
create
nono

Create a new file if it doesn't exist.

dest
yes

The file to modify.


aliases: name, destfile
follow

(added in 1.8)

nono

This flag indicates that filesystem links, if they exist, should be followed.

group
no

name of the group that should own the file/directory, as would be fed to chown

insertafter
noEOF

If specified, the block will be inserted after the last match of specified regular expression. A special value is available; for inserting the block at the end of the file. If specified regular expresion has no matches, will be used instead.

insertbefore
no

If specified, the block will be inserted before the last match of specified regular expression. A special value is available; for inserting the block at the beginning of the file. If specified regular expresion has no matches, the block will be inserted at the end of the file.

marker
no# {mark} ANSIBLE MANAGED BLOCK

The marker line template. "{mark}" will be replaced with "BEGIN" or "END".

mode
no

mode the file or directory should be. For those used to /usr/bin/chmod remember that modes are actually octal numbers (like 0644). 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, or ).

owner
no

name of the user that should own the file/directory, as would be fed to chown

selevel
nos0

level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the . feature works as for seuser.

serole
no

role part of SELinux file context, feature works as for seuser.

setype
no

type part of SELinux file context, feature works as for seuser.

seuser
no

user part of SELinux file context. Will default to system policy, if applicable. If set to , it will use the portion of the policy if available

state
nopresent

Whether the block should be there or not.

validate
noNone

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.

Examples

- name: insert/update "Match User" configuation block in /etc/ssh/sshd_configblockinfile: dest: /etc/ssh/sshd_configblock: | 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: dest: /etc/network/interfacesblock: | iface eth0 inet static address 192.168.0.1 netmask 255.255.255.0
- name: insert/update HTML surrounded by custom markers after <body> lineblockinfile: dest: /var/www/html/index.htmlmarker: "<!-- {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 markersblockinfile: dest: /var/www/html/index.htmlmarker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"content: ""

Requirements

None.

Role Variables

None.

Dependencies

None.

Example Playbook

Complete playbook that makes SSH password authentication for specific user prohibited, then restarts sshd if needed.

--- - hosts: allremote_user: ansible-agentsudo: yesroles: - yaegashi.blockinfiletasks: - name: Prohibit SSH password authentication for $SUDO_USERblockinfile: dest: /etc/ssh/sshd_configbackup: yescontent: | Match User {{ansible_env.SUDO_USER}} PasswordAuthentication nonotify: Restart sshdhandlers: - name: Restart sshdservicename: sshstate: restarted

License

GPLv3+

Author Information

YAEGASHI Takeshi

Sours: https://github.com/yaegashi/ansible-role-blockinfile

Blockinfile examples ansible

Ansible blockinfile module is used to insert/update/remove a block of lines. The block will be surrounded by a marker, like begin and end, to make the task idempotent.

If you want to modify/ insert only a line, use lineinfile module. You can find the documentation in

You can find more details of blockinfile module in Ansible documentation.  This post gives a basic idea and some examples of doing config management with blockinfile module.

Inserting a Block of Lines

To insert a block of lines, at the very least, you need to give the Path of the file and a block of lines.

Here I am trying to insert the block of two lines in the file block_output.txt. The dest parameter sets the path of remote file and block parameter sets the block of lines.

- hosts: blocks tasks: - name: Ansible Insert multiple lines using blockinfile blockinfile: dest: /home/mdtutorials2/block_output.txt block: | These lines are added by blockinfile module Check out the marker lines backup: yes

Note 1: Use path parameter if you have Ansible version >2.3.

Note 2: If you don’t give the block parameter, then any block with the default markup line will be removed.

Note 3: By default, the block will be inserted at the end of the file.

Note 4: ‘|’ is the literal block character in YAML.

Note 5: Use the backup parameter to create a backup file if something changed. It can help if any failure happened. The backup file includes the timestamp. eg: [email protected]:44:27

In the block_output.txt below, you can see the inserted lines. Note that, above and below the inserted block is a marker ‘#BEGIN/END ANSIBLE MANAGED BLOCK’. This makes sure that on subsequent runs the block won’t be inserted again. You can have multiple managed blocks using different markup. For instance, you can see in the execution summary below, for the second run, that there is no change.

Inserting a group of lines using blockinfile module

Customized marker line

You can customize the marker line. This is helpful when you need to control multiple blocks in the same file. The unique marker lines will make sure each blockinfile operations change only the intended blocks.

Or maybe ‘#’ is not the comment character in the particular file you need to change.

You can customize the marker line like below.

marker:"<!--{mark} Adding IP address -->"

This will add the marker ‘BEGIN Adding IP address’ and ‘End Adding IP address’ to the block. You can change the ‘{mark}’ also.

Updating a Block of Lines

You can update an inserted block of lines by changing the content of the block parameter. Ansible first the check if a block with the marker is present. Then it will update the remote file with the new block.

- hosts: blocks tasks: - name: Updating a line using Ansible blockinfile module blockinfile: dest: /home/mdtutorials2/config_management.txt marker: <!-- {mark} Adding IP address --> block: | These lines were updated by blockinfile module Check out the marker lines

The above task will update the block with the given marker line.

Removing a block of lines

You can remove a block by choosing the absent option for the state parameter.

- hosts: blocks tasks: - name: Removing a line using blockinfile blockinfile: dest: /home/mdtutorials2/block_output.txt marker: <!-- {mark} Adding IP address --> state: absent

Adding Block After/Before a Particular Pattern Using Regex

By default, the block will be inserted at the EOF. But we can control where to insert using Regex.You can either insert below a pattern using the insertafter parameter or above a line using the insertbefore parameter.

In the below script I am trying to insert a block, before the pattern “line starting with line no”.

- hosts: blocks tasks: - name: Ansible blockinfile insertafter and insertbefore blockinfile: dest: /home/mdtutorials2/block_output.txt block: | Line inserted using Regex Ansible blockinfile module insertbefore: "^line no"

blockinfile using regex

Here there are multiple lines with the regex “^line no”. So the block was inserted just before the last occurrence of the pattern, “line no 3”.

Note 1: If the same pattern occurs multiple times, then the last match will be taken.

Note 2: You can insert at the beginning of the file using insertbefore: BOF

Giving variables in the block

You can add variables in the blocks by just enclosing the variable within {{ }}. The following example will replace the variable ‘var1’ with the value before modifying the remote file.

- hosts: blocks vars: var1: 'world' tasks: - name: Ansible blockinfile variable example blockinfile: dest: /home/mdtutorials2/block_output.txt marker: <!-- {mark} variable replace --> block: | hello {{ var1 }}

Adding Multiple blocks using with_items

We can add multiple blocks in a file using blockinfile and with_items. But one of the common mistakes people make is not using a unique marker. If you use a marker like below, then the content will be overwritten multiple times.

marker: <!-- {mark} blockinfile with items -->

To solve this, you can use a unique marker like below.

- hosts: blocks tasks: - name: Using Ansible blockinfile with_items blockinfile: dest: /home/mdtutorials2/block_output.txt block: | {{ item.name }} -- {{ item.line }} marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}" with_items: - { name: line1, line: hello1 } - { name: line2, line: hello2 } - { name: line3, line: hello3 }

Ansible blockinfile with_items

Note 1: With_items should be written at the level of the module name. And not at the level of its parameters. If you get an error “the field ‘args’ has an invalid value, which appears to include a variable that is undefined.”, this might be the reason.

Inserting contents from an external file

You can also use the contents from an external file using the lookup plugin. The file should be available in your Ansible control machine.

block:"{{lookup('file','/home/user/localfile.txt')}}"

ISSUE:

If you get the following error,

blockinfile unsupported parameter for module: path

check your ansible version. If the version is below 2.3, use dest instead. It was renamed to ‘path‘ only in version 2.3]

For more details on how to change file contents, you can check the details of all the parameters in Ansible documentation.

Check out the Ansible user module  to see how to mange the user accounts in Linux.

Sours: https://www.mydailytutorials.com/ansible-blockinfile-module-adding-multiple-lines/
Ansible Tutorial Part 6 - Ansible Roles Explained with Examples - Create Your Ansible Roles

blockinfile – Insert/update/remove a text block surrounded by marker lines

ParameterChoices/DefaultsCommentsattributes

string

The attributes the resulting 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.

The operator is assumed as default, otherwise or operators need to be included in the string.


aliases: attr

backup

boolean

Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.

block

string

Default:

""

The text to insert inside the marker lines.

If it is missing or an empty string, the block will be removed as if were specified to .


aliases: content

create

boolean

Create a new file if it does not exist.

group

string

Name of the group that should own the file/directory, as would be fed to chown.

insertafter

string

If specified, the block will be inserted after the last match of specified regular expression.

A special value is available; for inserting the block at the end of the file.

If specified regular expression has no matches, will be used instead.

insertbefore

string

If specified, the block will be inserted before the last match of specified regular expression.

A special value is available; 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.

marker

string

Default:

"# {mark} ANSIBLE MANAGED BLOCK"

The marker line template.

will be replaced with the values (default="BEGIN") and (default="END").

Using a custom marker without the variable may result in the block being repeatedly inserted on subsequent playbook runs.

marker_begin

string

added in 2.5

Default:

"BEGIN"

This will be inserted at in the opening ansible block marker.

marker_end

string

added in 2.5

Default:

"END"

This will be inserted at in the closing ansible block marker.

mode

string

The permissions the resulting file or directory should have.

For those used to /usr/bin/chmod remember that modes are actually octal numbers. You must either add a leading zero so that Ansible's YAML parser knows it is an octal number (like or ) or quote it (like or ) so Ansible receives a string and can do its own conversion from string into number.

Giving Ansible a number without following one of these rules will end up with a decimal number which will have unexpected results.

As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, or ).

owner

string

Name of the user that should own the file/directory, as would be fed to chown.

path

path / required

The file to modify.

Before Ansible 2.3 this option was only usable as dest, destfile and name.


aliases: dest, destfile, name

selevel

string

Default:

"s0"

The level part of the SELinux file context.

This is the MLS/MCS attribute, sometimes known as the .

When set to , it will use the portion of the policy if available.

serole

string

The role part of the SELinux file context.

When set to , it will use the portion of the policy if available.

setype

string

The type part of the SELinux file context.

When set to , it will use the portion of the policy if available.

seuser

string

The user part of the SELinux file context.

By default it uses the policy, where applicable.

When set to , it will use the portion of the policy if available.

state

string

    Choices:
  • absent
  • present

Whether the block should be there or not.

unsafe_writes

boolean

Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target file.

By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted files, which cannot be updated atomically from inside the container and can only be written in an unsafe manner.

This option allows Ansible to fall back to unsafe methods of updating files when atomic operations fail (however, it doesn't force Ansible to perform unsafe writes).

IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.

validate

string

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 examples below.

The command is passed securely so shell features like expansion and pipes will not work.

Sours: https://docs.w3cub.com/ansible~2.9/modules/blockinfile_module

Similar news:

Ansible module blockinfile

The blockinfile module inserts "a piece of text" into the specified file, which is marked, that is, marks the text, so that the text can be found through "mark" in later operations, and then modify or delete it.

1, Common parameters

path:required, specifies the file to operate on.
Block: specifies a piece of text to be operated on. This parameter has a name of "content". Using content or block is the same.
Marker: insert a piece of text in the specified file, and ansible will automatically add two marks for the text, one is the start mark and the other is the end mark. By default, the start mark is "BEGIN ANSIBLE MANAGED BLOCK" and the end mark is "END ANSIBLE MANAGED BLOCK", and the marker parameter is used to customize "mark". For example, marker = {mark} test. After this setting, the start tag becomes a BEGIN test and the end tag becomes an END test.
State: the state parameter has two optional values, present and absent, which insert and delete the corresponding marked paragraphs.
insertafter: when inserting a piece of text, the text will be inserted at the end of the file by default. If you want to insert the text after a line, you can use this parameter to specify the corresponding line, or you can use a regular expression (python regular) to insert the text after the line that matches the regular expression. If more than one line of text can match the corresponding regular expression, the last one that satisfies the regular behavior shall prevail. The value of this parameter can also be set to EOF, indicating that the text is inserted at the end of the document.
Insert before: when inserting a piece of text, the text will be inserted at the end of the file by default. If you want to insert the text in front of a line, you can use this parameter to specify the corresponding line, or you can use a regular expression (python regular) to insert the text in front of the line that matches the regular expression. If more than one line of text can match the corresponding regular expression, the last regular behavior will prevail. The value of this parameter can also be set to BOF, indicating that the text is inserted at the beginning of the document.
backup: whether to back up the file before modifying it.
Create: whether to create the corresponding file when the file to be operated does not exist.

Two, example

Example 1

[[email protected] ~][[email protected] ~] systemctl start mariadb systemctl start httpd

Example 2

[[email protected] ~][[email protected] ~] systemctl start mariadb systemctl start httpd

Example 3
On the basis of the above command, execute the following command:

[ro[email protected] ~]

Because when executing this command, the text block corresponding to the "{mark} serve to start" tag already exists in the file, and at the same time, the content corresponding to the block parameter is different from the content of the previous text block, so in this case, the content in the corresponding text block will be updated without inserting a new text block again, which is equivalent to updating the content in the original text block Content.

[[email protected] ~] systemctl start mariadb

Example 4
On the basis of the above command, execute the following command:

[[email protected] ~]

When executing this command, the text block corresponding to the "{mark} service to start" tag already exists in the file. At the same time, the content corresponding to the block parameter is empty. At this time, the blockinfile module will delete the text block corresponding to the tag, so the return information is "Block removed".
Example 5

[[email protected] ~]

Use to set the value of state to absent to delete the text block of the corresponding tag.
By default, the text block is inserted at the end of the file. We can also insert the text block at the specified position, for example, at the beginning of the file, or match the corresponding row according to the regular expression, and then insert the text block at the front or back of the matched row.
Example 6
If you want to insert a text block at the beginning of a document, you can use the insertbefore parameter to set its value to BOF, which means Begin Of File:

[[email protected] ~]

Example 7
If you use the following command to insert a text block to the end of the document, as in the default operation, set the insertafter parameter to EOF to End Of File:

[[email protected] ~]

Example 8
Use the following command to match lines with regular expressions, and insert the text block after "lines starting with" ×! / bin/bash ":

[[email protected] ~]

Example 9
Using the backup parameter, you can back up the file before modifying the file. The backed up file will be time stamped based on the original file name:

[[email protected] ~]

Example 10
Using the create parameter, if the specified file does not exist, create it:

[[email protected] ~]

--Blueicex 2020/2/2 17:55 [email protected]

Sours: https://programming.vip/docs/ansible-module-blockinfile.html


534 535 536 537 538