Reputation: 11
I have a var, i want to write content of var to a line in file.
Example: var: TEXT_NEED_TO_ADD
file before added:
some_line
text text mark text text
some_line
file after added:
some_line
text text mark TEXT_NEED_TO_ADD text text
some_line
What should i do?
Sorry for My English.
Upvotes: 1
Views: 1673
Reputation: 358
If your file is static(by which i mean that you want to insert the TEXT_NEED_TO_ADD just once during deploy) the best way (and easiest to maintain) to go about is creating a jinja2 template file and using it in your role.
So your file structure should be:
your_role/
templates/
my_file_template.j2
tasks/
main.yml
and your files should look like this:
main.yml
- name: copy file and fill it
template: src=my_file_template.j2 dest="/home/user/my_file"
my_file_template.j2
some_line
text text mark {{TEXT_NEED_TO_ADD}} text text
some_line
this way ansible will insert the contents of the variable into a file(in a place of {{TEXT_NEED_TO_ADD}}) before copying it into location specified by dest. You can use as many variables in jinja template as you wish. Ansible also supports many filters and other usefull tools (such as loops for example). But i guess using sed
would be fine too. Depends on what you want to achieve.
you can read more about template module here
and you can read more about templates here
Upvotes: 2
Reputation: 4606
You can do some magic with sed
command:
- name: insert string in file
shell: sed '/mark/a {{ TEXT_NEED_TO_ADD }}' filename
I'm not really good in sed manipulation, but the general idea is: if you can't do it with Ansible, try to do it in Bash and if you could - setup Ansible to do it for you. Or you can write Ansible Module to do it, but often Bash is really enough.
Upvotes: 1