How to strip newline from shell command's standard output run via ansible
Solution 1
In the documentation of raw_module, it asks to use it only in specific cases:
Executes a low-down and dirty SSH command, not going through the module subsystem. This is useful and should only be done in two cases. The first case is installing
python-simplejson
on older (Python 2.4 and before) hosts that need it as a dependency to run modules, since nearly all core modules require it. Another is speaking to any devices such as routers that do not have any Python installed. In any other case, using theshell
orcommand
module is much more appropriate. Arguments given to raw are run directly through the configured remote shell.
So, I tested simple echo calls with raw
and shell
modules:
- name: System setup
hosts: 127.0.0.1
connection: local
tasks:
- name: simple print hello
raw: echo 'hello'
register: my_info
- debug:
msg: '{{ my_info.stdout }}'
and it outputs with a new line:
TASK: [debug ] ****************************************************************
ok: [127.0.0.1] => {
"msg": "hello\n"
}
and by using the shell
module:
- name: System setup
hosts: 127.0.0.1
connection: local
tasks:
- name: simple print hello
action: shell echo 'hello'
register: my_info
- debug:
msg: '{{ my_info.stdout }}'
and this results in:
TASK: [debug ] ****************************************************************
ok: [127.0.0.1] => {
"msg": "hello"
}
And, you can see the difference in the output.
Solution 2
You can use the built-in filters of Jinja2 to achieve this. Specifically, use trim
, e.g.:
- debug: msg='{{ my_info.stdout | trim}}'
Solution 3
You could remove the newline from stdout, using
grep 'CONFIG_PARAMS' /path/to/the/file | head -n 1 | tr -d '\n'
If you run this on a command-line you'll see something like
me@machine:~ > echo cat | tr -d '\n'
catme@machine:~ >
because linux is adding the newline.
Ankit Kulkarni
I am a enthusiast guy towards CS and new Tech. I work as Devops Engineer and I love to write code.
Updated on June 17, 2022Comments
-
Ankit Kulkarni almost 2 years
So I have a scenario where I am executing a shell command on a machine using ansible to get some information on standard output . I am using
register
to log its result in a variablemy_info
and printmy_info
usingdebug
, I am seeing its result with\n
appended to it (Ansible has appended \n .Same command on linux do not appends \n" ).When I use themy_info
in templates for a config it prints a new line in config hence messing up my config .Here is how the code and output goes .
Ansible code :
- name: calculate range address start raw: grep 'CONFIG_PARAMS' /path/to/the/file | head -n 1 register: my_info
Output :
ok: [My_HOST] => { "msg": "CONFIG_PARAMS\n" }
How can we strip the space from this output or possibly make a change in template so that new line don't gets printed .