Giter VIP home page Giter VIP logo

ansible-role-blockinfile's Introduction

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/interfaces
    block: |
      iface eth0 inet static
          address 192.168.0.1
          netmask 255.255.255.0

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

# BEGIN ANSIBLE MANAGED BLOCK
iface eth0 inet static
    address 192.168.0.1
    netmask 255.255.255.0
# END ANSIBLE MANAGED BLOCK

It uses marker lines # {BEGIN/END} ANSIBLE MANAGED BLOCK as default. You can specify alternative marker lines by marker 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.

parameter required default choices comments
backup
no no
  • yes
  • no
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 state were specified to absent.

    aliases: content
    create
    no no
    • yes
    • no
    Create a new file if it doesn't exist.
    dest
    yes
      The file to modify.

      aliases: name, destfile
      follow
      (added in 1.8)
      no no
      • yes
      • no
      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
        no EOF
        • EOF
        • *regex*
        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 expresion has no matches, EOF will be used instead.
        insertbefore
        no
        • BOF
        • *regex*
        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 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, u+rwx or u=rw,g=r,o=r).
            owner
            no
              name of the user that should own the file/directory, as would be fed to chown
              selevel
              no s0
                level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the range. _default feature works as for seuser.
                serole
                no
                  role part of SELinux file context, _default feature works as for seuser.
                  setype
                  no
                    type part of SELinux file context, _default feature works as for seuser.
                    seuser
                    no
                      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
                      state
                      no present
                      • present
                      • absent
                      Whether the block should be there or not.
                      validate
                      no None
                        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_config
                          blockinfile:
                            dest: /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:
                            dest: /etc/network/interfaces
                            block: |
                              iface eth0 inet static
                                  address 192.168.0.1
                                  netmask 255.255.255.0
                        - name: insert/update HTML surrounded by custom markers after <body> line
                          blockinfile:
                            dest: /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:
                            dest: /var/www/html/index.html
                            marker: "<!-- {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: all
                          remote_user: ansible-agent
                          sudo: yes
                          roles:
                            - yaegashi.blockinfile
                          tasks:
                            - name: Prohibit SSH password authentication for $SUDO_USER
                              blockinfile:
                                dest: /etc/ssh/sshd_config
                                backup: yes
                                content: |
                                  Match User {{ansible_env.SUDO_USER}}
                                  PasswordAuthentication no
                              notify: Restart sshd
                          handlers:
                            - name: Restart sshd
                              service
                                name: ssh
                                state: restarted

                        License

                        GPLv3+

                        Author Information

                        YAEGASHI Takeshi

                        ansible-role-blockinfile's People

                        Contributors

                        yaegashi avatar

                        Stargazers

                         avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

                        Watchers

                         avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

                        ansible-role-blockinfile's Issues

                        blockinfile with_items

                        Hello, I have hard time to figure out how to get the blocks properly formatted.

                        With the task

                        - name: Configure Direcotries in {{apache_conf_path}}/httpd.conf
                          blockinfile:
                            dest: "{{apache_conf_path}}/httpd.conf"
                            backup: "yes"
                            marker: "# {mark} ANSIBLE MANAGED BLOCK"
                            insertafter: "# <Directory> blocks below."
                            block: |
                              {{item}}
                          with_items: "{{apache_Directory_blocks}}"
                        

                        and variable

                        apache_Directory_blocks:                                                                                                             
                          - <Directory "/usr/local/www/roundcube">                                                                                           
                              Options Indexes FollowSymLinks                                                                                                 
                            </Directory>                                                                                                                     
                        

                        I see the the block in one line

                        <Directory "/usr/local/www/roundcube"> Options Indexes FollowSymLinks </Directory>
                        

                        What am I missing? Thank you for your effort!

                        -vlado

                        Have an option to add newline to the end of marker

                        I've found that using the blockinfile it doesn't add a newline to the end of the marker if it also happens to be the end of the file.

                        The newline acts as the eol, or the “end of line” character and it's required for POSIX.

                        Ideally it should automatically detects that it is the end of the then adds the character. This is especially useful for adding a block of text using this module on an empty file.

                        Add insertafter/insertbefore options to insert a block at an arbitrary position

                        Hi @yaegashi, I'm opening this Feature Request inspired by the TODO chapter of the README.
                        I really would like to see this feature in 0.3 version.

                        P.s: thank you for your great module. Using your module it's the only sane way to manage a big /etc/hosts with Ansible (in my company nobody loves DNS servers).
                        I think we should request to add it to the official ansible-core-modules (or extra) repository!

                        KeyError: 'follow'

                        With these two lines:

                        if module.boolean(params['follow']):
                              dest = os.path.realpath(dest)
                        

                        Ansible (1.7.2) fails with:

                        Traceback (most recent call last):
                          File "<stdin>", line 1591, in <module>
                          File "<stdin>", line 153, in main
                        KeyError: 'follow'
                        

                        Setting a follow parameter throws:
                        msg: unsupported parameter for module: follow

                        Handling escape sequence in ansible 1.7

                        The following code block:

                        if present and block:
                            # Escape seqeuences like '\n' need to be handled in Ansible 1.x                              
                            if ANSIBLE_VERSION.startswith('1.'):                                                         
                                block = re.sub('', block, '')                                                            
                            blocklines = [marker0] + block.splitlines() + [marker1]
                        

                        will crash under my test system with Ansible 1.7.

                        ANSIBLE_VERSION is not found and throws a NameError; my guess is that a newer version of ansible will import ANSIBE_VERSION with the wildcard imports but an older version does not.
                        The program seems to work after removing the entire if block.

                        Module doesn't work with PARAMETER=

                        - name: Add server as client
                          blockinfile:
                            dest: /etc/munin/munin.conf
                            state: present
                            marker: "#{mark} ANSIBLE MANAGED BLOCK"
                            block: |
                              [{{ ansible_hostname }}]
                                  address {{ ansible_eth1.ipv4.address }}
                                  use_node_name yes

                        This code work.

                        but when I try to use = instead of : it doesn't work anymore.

                        - name: Add server as client
                          blockinfile: >
                            dest=/etc/munin/munin.conf
                            state=present
                            marker="#{mark} ANSIBLE MANAGED BLOCK"
                            block= |
                              "[{{ ansible_hostname }}]
                                address {{ ansible_eth1.ipv4.address }}
                                use_node_name yes"

                        I get this error :
                        msg: this module requires key=value arguments (['dest=/etc/munin/munin.conf', 'state=present', 'marker=#{mark} ANSIBLE MANAGED BLOCK', 'block=', '|', '[monitoring-server]\naddress 192.168.35.17\nuse_node_name yes'])

                        Omitting "marker"

                        Sometimes it's useful to add markers, other times, not. Is there any way to omit the marker lines?

                        Doesn't work with ansible 1.x

                        Hello,

                        I tried to use the most recent version 0.6 of this module with ansible 1.7.1 and 1.5.4 and it doesn't work at all:

                        - name: Add DB Config
                          blockinfile:
                            dest: "{{ test_rootfs }}/blockinfile"
                            block: |
                                DATABASES={
                                    'default': dbname
                                }
                        
                        ERROR: blockinfile is not a legal parameter in an Ansible task or handler
                        

                        After much troubleshooting I realized that role/module Python script file was blockinfile.py, when it's supposed to be blockinfile:

                        .
                        ├── CONTRIBUTING.md
                        ├── library
                        │   └── blockinfile.py
                        ├── meta
                        │   └── main.yml
                        ├── README.md
                        └── tests
                            ├── expected
                            ├── fixtures
                            ├── hosts
                            ├── run.sh
                            ├── test-basic.yml
                            ├── test-block.yml
                            ├── test-follow.yml
                            ├── testing
                            ├── test-insertab.yml
                            ├── test-replace.yml
                            └── test-state.yml
                        

                        Even then, when blockinfile.py was renamed to blockinfile ansible 1.5.4 would run into this problem:

                        fatal: [127.0.0.1] => imported module support code does not exist at /usr/lib/python2.7/dist-packages/ansible/module_utils/splitter.py
                        

                        Ansible version 1.7.1 has the required splitter.py utility but even so there was one more issue:

                        failed: [127.0.0.1] => {"failed": true, "parsed": false}
                        invalid output was: 
                        SUDO-SUCCESS-qkewojdkkysbtyyflfhsnifqgvkpjnrg
                        Traceback (most recent call last):
                          File "/home/ansiblemgr/.ansible/tmp/ansible-tmp-1459262324.65-150912085331989/blockinfile", line 1833, in <module>
                            main()
                          File "/home/ansiblemgr/.ansible/tmp/ansible-tmp-1459262324.65-150912085331989/blockinfile", line 226, in main
                            if ANSIBLE_VERSION.startswith('1.'):
                        NameError: global name 'ANSIBLE_VERSION' is not defined
                        debug3: mux_client_read_packet: read header failed: Broken pipe
                        debug2: Received exit status from master 0
                        Shared connection to 127.0.0.1 closed.
                        

                        I edited the module Python script blockinfile(.py) and commented out the problematic conditional as in my case I have ansible 1.7 and it's essentially superfluous:

                            if present and block:
                                # Escape seqeuences like '\n' need to be handled in Ansible 1.x
                                #if ANSIBLE_VERSION.startswith('1.'):
                                #    block = re.sub('', block, '')
                                block = re.sub('', block, '')
                                blocklines = [marker0] + block.splitlines() + [marker1]
                            else:
                                blocklines = []
                        

                        Then it finally worked.

                        I haven't tested any other parameters outside what is shown in the beginning of this report.

                        This module is either awfully broken or woefully undocumented. So, please, either fix these issues or update documentation and clearly indicate that 2.0 is the only supported version.

                        Ivan

                        Please add install instructions to README.md

                        I want to use this module, but don't know how to install this at all.

                        I get an (expected) error when using homebrew'd ansible, b/c I didn't install this yet (and don't know how).

                        ERROR: blockinfile is not a legal parameter in an Ansible task or handler
                        

                        Spacing in blocks does not work as expected

                        - name: Add logstash-forwarder to datadog process monitoring
                          blockinfile:
                            dest: /etc/dd-agent/conf.d/process.yaml
                            block: |
                              - name: logstash-forwarder
                                search_string: ['logstash-forwarder']
                                exact_match: false
                                thresholds:
                                  # critical if no server.py is running
                                  critical: [1, 1]

                        this code for example will be aligned to the first line in the block. this means that the result in the yaml would be:

                        - name: logstash-forwarder
                          search_string: ['logstash-forwarder']

                        notice that spacing. the - name is at the beginning of the line and search_string is two spaces behind.

                        This breaks the yaml format and should be handled.

                        Recommend Projects

                        • React photo React

                          A declarative, efficient, and flexible JavaScript library for building user interfaces.

                        • Vue.js photo Vue.js

                          🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

                        • Typescript photo Typescript

                          TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

                        • TensorFlow photo TensorFlow

                          An Open Source Machine Learning Framework for Everyone

                        • Django photo Django

                          The Web framework for perfectionists with deadlines.

                        • D3 photo D3

                          Bring data to life with SVG, Canvas and HTML. 📊📈🎉

                        Recommend Topics

                        • javascript

                          JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

                        • web

                          Some thing interesting about web. New door for the world.

                        • server

                          A server is a program made to process requests and deliver data to clients.

                        • Machine learning

                          Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

                        • Game

                          Some thing interesting about game, make everyone happy.

                        Recommend Org

                        • Facebook photo Facebook

                          We are working to build community through open source technology. NB: members must have two-factor auth.

                        • Microsoft photo Microsoft

                          Open source projects and samples from Microsoft.

                        • Google photo Google

                          Google ❤️ Open Source for everyone.

                        • D3 photo D3

                          Data-Driven Documents codes.