Ansible register variable not defined - ansible

Before running a patching playbook, I ran the playbook with the "--check" option as a dry run. However, one of the plays within the playbook to check whether the group needs a reboot, doesn't register the "reboot_hint" variable as intended
- name: check for reboot
shell: needs-restarting -r
register: reboot_hint
failed_when: reboot_hint.rc > 1
- name: debug, show the reboot hint variable
debug:
var:
- reboot_hint.rc
- reboot_hint
I get the message: ""VARIABLE IS NOT DEFINED!"" for the run.
What could be causing this? I am expect a return value of "1" or "0". I do get that when I go into the command line, run the "needs-restarting -r" and "echo $?
No core libraries or services have been updated.
Reboot is probably not necessary.
> echo $?
0

You're running --check and thus the shell command doesn't run. Because the shell command doesn't run there's nothing to register.
You can read more about this in https://docs.ansible.com/ansible/latest/user_guide/playbooks_checkmode.html#enabling-or-disabling-check-mode-for-tasks
A simple fix is adding check_mode: no, e.g.
- name: check for reboot
check_mode: no
shell: needs-restarting -r
register: reboot_hint
failed_when: reboot_hint.rc > 1
This forces the task to run even when check-mode is enabled.

Related

How to emulate raw command with EOF?

I am trying to emulate this behavior with Ansible raw command but I could not find any feature that achieve this
ssh user#host.com <<EOF
command
exit
EOF
You are simply sending the script:
command
exit
To the remote host. The <<EOF and EOF parts are parsed by your local shell and aren't part of the command. The equivalent ansible task would be:
- raw: |
command
exit
In most cases (if the remote target is running a semi-standard shell), you won't need the exit either; the script will exit after the last command completes.
You don't need to send a multiline commands via ssh, perhaps you have connected with ssh already with ansible when you set ansible_connection variable, e.g. in your inventory file:
[my_host_group]
host.com
[my_host_group:vars]
ansible_connection=ssh
ansible_become_user=root
ansible_ssh_user=user
Then execute a tasks with bash:
- name: Executing multiline command on host.com under user
ansible.builtin.shell: command
delegate_to: "{{ groups['my_host_group'][0] }}"
become: False
Or just use ansible.builtin.command module instead of ansible.builtin.shell if your command is simple and not multi line.
You don't need an exit at the end of your script either (until you want to change an exit code and return them to ansible). 'Failed when' conditions is your firend:
- name: Executing multiline command on host.com under user
ansible.builtin.shell: command
delegate_to: "{{ groups['my_host_group'][0] }}"
register: your_script_results
ignore_errors: True
become: False
- name: Print an exit code on script error
ansible.builtin.debug:
msg: "Script was failed with {{ your_script_results.rc }} exit code"
when: your_script_results.failed

Printing command stdout on console during runtime

Sometimes I have to wait very long during running ansible command. For example such command can be executed 30 minutes for my module:
- name: make project
shell: make -j4 install
args:
chdir: "{{ project_dir }}/build"
I would like to see the stdout of this command live, during runtime, not when the command has finished (I see the output when the command has finished, but I need responsiveness, so I'm not interested in something like -v, -vvv or -vvvv). Is it possible to force ansible to print the output during running command (not to buffer it and not to print it at the end)?
You can't print the output while the command runs, but you can print it after the command finished:
- name: make project
shell: make -j4 install
args:
chdir: "{{ project_dir }}/build"
register: out
ignore_errors: yes
- name: print output
debug:
msg: "{{ out.stdout }}"
- name: fail when make failed
fail:
msg: "make task failed"
when: out.rc != 0
The ignore_errors: yes and the fail-task are there, so the output will get printed before your play fails in case the make-task fails.
You should also consider using the make module instead of running make in a shell.

How to run a shell function as a command in Ansible playbook?

I have a function in shell script and i want to use it in my ansible playbook
my shell script -
wait_for_apt_locks () {
while sudo fuser /var/{lib/cache/apt/archives}/{lock,lock-frontend} >/dev/null 2>&1; do
echo "Waiting for apt locks"
sleep 1
done
i want to use this function wait_for_apt_locks in my playbook wait.yml
is the below the right way to use it?
- name: source /tmp/function.sh
shell: |
source /tmp/functions.sh
wait_for_apt_locks
I don't have any suggestions regarding loading bash functions - if your example works, then it works!
But do note that Ansible has a wait_for module used for monitoring ports or files.
Perhaps this is a more Ansible-native solution for dealing with lock files.
From https://docs.ansible.com/ansible/latest/modules/wait_for_module.html#examples:
- name: Wait until the lock file is removed
wait_for:
path: /var/lock/file.lock
state: absent
If you are creating the shell script for the sole purpose of calling it here, you can skip the script file and simply execute the logic inline. At the end of the day, if it works it works.
- name: Run a shell command inline
become: true
command: >
while fuser {lib/cache/apt/archives}/{lock,lock-frontend} >/dev/null 2>&1; do
echo "Waiting for apt locks";
sleep 1;
done
ignore_errors: no
args:
chdir: /var
Documentation

Using ssh-keyscan in shell module does not produce any output in Ansible

I'm trying to follow this solution to add use the shell module and ssh-keyscan to add a key to my known_hosts file of a newly created EC2 instance.
After trying to do this multiple ways as listed on that question I eventually ran just the ssh-keyscan command using the shell module without the append. I am getting no output from this task:
- name: accept new ssh fingerprints
shell: ssh-keyscan -H {{ item.public_ip }}
args:
executable: /bin/bash
with_items: "{{ ec2.instances }}"
register: keyscan
- debug: var=keyscan
Debug here shows nothing in stdout and stdout_lines and nothing in stderr and stderr_lines
Note: I tried running this with the bash as the executable shown after reading that the shell module defaults to /bin/sh which is the dash shell on my Linux Mint VirtualBox. But it's the same regardless.
I have tested the shell command with the following task and I see the proper output in stdout and stdout_lines:
- name: test the shell
shell: echo hello
args:
executable: /bin/bash
register: hello
- debug: var=hello
What is going on here? Running ssh-keyscan in a terminal (not through Ansible) works as expected.
EDIT: Looking at the raw_params output from debug shows ssh-keyscan -H x.x.x.x and copying and pasting this into the terminal works as expected.
The answer is that it doesn't work the first time. While researching another method I stumbled across the retries keyword in ansible that allows a retry of whatever command. I tried this and on attempt number 2 in the retry loop it is working.

Retrieve env variable of target node using ansible

I am trying to get env variale JAVA_HOME value of a target node using ansible.
- name: Copy JAVA_HOME location to variable
command: bash -c "echo $JAVA_HOME"
sudo: yes
register: java_loc
When i use, java_loc.stdout value in another task, it is showing blank value. How can i get that env variable and use it in another task?
I need to copy files to JAVA dir which is present in JAVA_HOME.
Ansible logins via SSH using non-login shell. Probably your problem is that you defined the environment variable on $HOME/.bash_profile or some other file that requires login shell, so you need to add the "-l" flag to "/bin/bash":
---
- name: Copy JAVA_HOME location to variable
command: /bin/bash -l -c "echo $JAVA_HOME"
sudo: no
register: java_loc
- name: show debug
debug: var=java_loc
Please, give it a try and let me know,
If your Java is sufficiently recent to have jrunscript, you can obtain the Java Path from your Java installation, avoiding any dependency on your environment. The code below does this, and doesn't fail if there's no jrunscript.
- name: Detemine Java home
command: 'jrunscript -e java.lang.System.out.println(java.lang.System.getProperty(\"java.home\"));'
changed_when: False
ignore_errors: True
register: locate_java_home
- name: Set a variable for Java home
set_fact:
java_home: "{{ (locate_java_home.rc == 0) | ternary(locate_java_home.stdout, '') }}"
The solution is based on the proposal made here.

Resources