Reputation: 47
When i use blockinfile loop to append /etc/environment file it only adds last key and value of item from loop variable rather then adding all of it.
I am trying to modify files using Blockinfile module in roles main.yml:
- name: Add proxy to global /etc/environments
blockinfile:
path: "/etc/environment"
block: |
export {{item.key}}={{item.value}}
loop: "{{proxy_details}}"
my vars/main.yaml looks like this:
proxy_details:
- key: http_proxy
value: "http://"{{ProxyHost}}":"{{ProxyPort}}""
- key: https_proxy
value: "http://"{{ProxyHost}}":"{{ProxyPort}}""
my group_vars/all looks like this:
ProxyHost: test.com
ProxyPort: 9999
Upvotes: 0
Views: 897
Reputation: 28553
See the last example in the documentaion at https://docs.ansible.com/ansible/latest/modules/blockinfile_module.html. You need to use a custom marker for each item so Ansible knows where each one is in the file to replace it.
Per documentation note:
When using ‘with_*’ loops be aware that if you do not set a unique mark the block will be overwritten on each iteration.
The example is:
- name: Add mappings to /etc/hosts
blockinfile:
path: /etc/hosts
block: |
{{ item.ip }} {{ item.name }}
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"
loop:
- { name: host1, ip: 10.10.1.10 }
- { name: host2, ip: 10.10.1.11 }
- { name: host3, ip: 10.10.1.12 }
You could modify yours to be:
- name: Add proxy to global /etc/environments
blockinfile:
path: "/etc/environment"
marker: "# {mark} ANSIBLE MANAGED BLOCK FOR {{item.key}}"
block: |
export {{item.key}}={{item.value}}
loop: "{{proxy_details}}"
Upvotes: 1