Ansible – How to Use Blockinfile Module to Insert Lines of Code

ansibleansible-playbookshell-scripting

I try to insert lines of code (shell script) with Ansible blockinfile module.

name: Customized prompt
blockinfile:
path: /etc/profile.d/customized_prompt.sh
create: yes
block: |

#!/bin/bash

# customized prompt normal user and root

if (( "$(id -u)" == "1000" ))
then
    PS1="[\u@\H \w]$ "
elif (( "$(id -u)" == "0" ))
then
    PS1="[\u@\H \w]# "
fi

I have this Ansible error

[admin@srvansible /etc/ansible]$ ansible-playbook playbook_prompt.yml --ask-become-pass
BECOME password: 
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)

Syntax Error while loading YAML.
could not find expected ':'

The error appears to be in '/etc/ansible/roles/utilities/tasks/main.yml': line 14, column 4, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

if (( "$(id -u)" == "1000" ))
then
^ here

I need help please 🙂

thank you

Best Answer

YAML needs to be properly indented.

Try this:

name: Customized prompt
blockinfile:
  path: /etc/profile.d/customized_prompt.sh
  create: yes
  block: |
    if (( "$(id -u)" == "1000" ))
    then
        PS1="[\u@\H \w]$ "
    elif (( $(id -u)" == "0" ))
        PS1="[\u@\H \w]# "
    fi