Ansible fatal error while trying to print the state of firewalld - ansible

Here, i am trying to print the status of the firewall-cmd --state command , but a fatal error is being thrown.
name: Check firewall status
hosts: st
tasks:
- name: Check status of firewall
command: firewall-cmd --state
register: status
- name: Print version
debug:
msg: "Status = {{ status.stdout }}"
State is "not running" in the remote host. But am not getting the result.
I get the following output
fatal: [borexample.com]: FAILED! => {"changed": true, "cmd": ["firewall-cmd", "--state"], "delta": "0:00:00.189023", "end": "2018-09-16 11:40:17.319482", "msg": "non-zero return code", "rc": 252, "start": "2018-09-16 11:40:17.130459", "stderr": "", "stderr_lines": [], "stdout": "\u001b[91mnot running\u001b[00m", "stdout_lines": ["\u001b[91mnot running\u001b[00m"]}
How should i modify the code so that i get only the state ?

I prefer using failed_when: to control your output rc. More info at Ansible Documentation. But you can also use ìgnore_errors: true
Check error codes in the Firewall-cmd Documentation to see which codes adding to your playbook.
In your scenario could be good doing:
- name: Check status of firewall
command: firewall-cmd --state
register: status
failed_when:
- status.rc != 0
- status.rc != 252
Even you can go further and use failed_when: false to avoid the command failing.

The ignore_errors suggested by Baptiste Mille-Mathias would allow you to continue, but then you would like to "debug" {{ status.stderr }}, as in that ase stdout would be empty.

Related

Vagrant execution errors while ansible molecule testing

I am getting below error (/bin/sh: nslookup: command not found ) when i am using vagrant for ansible code testing using molecule testig
TASK [Query nslookup own domain] ***********************************************
fatal: [ vagrant01 ]: FAILED! => {"changed": true, "cmd": "nslookup `hostname --fqdn`", "delta": "0:00:00.012528", "end": "2021-10-21 13:42:40.197574", "msg": "non-zero return code", "rc": 127, "start": "2021-10-21 13:42:40.185046", "stderr": "/bin/sh: nslookup: command not found", "stderr_lines": ["/bin/sh: nslookup: command not found"], "stdout": "", "stdout_lines": []}
PLAY RECAP
so it seems nslookup is not installed
You can add a task to install the necessary tools
- name: Install nslookup
apt:
name: dnsutils
state: present
If you are on red-hat distro you need following package
- name: Install nslookup
yum:
name: bind-utils
state: present
or if you want to distribute any bistro you can add both
- name: Install nslookup for ubuntu
apt:
name: dnsutils
state: present
when: ansible_os_family == 'Debian'
- name: Install nslookup for redhat family
yum:
name: bind-utils
state: present
when: ansible_os_family == 'RedHat'

Ansible run a task based on something in output

I'm new in Ansible and I try to do some practice playbook. I write a playbook to deploy a Docker container as follows. I write a task in the block section if an error happened, run a task in the rescue section based on Failed message content. For example, I want to run a specific task to delete an existing container if the Failed message is something like this:
failed: [192.168.1.140] (item=stderr_lines) => {"changed": true, "cmd": ["docker", "run", "-itd", "--name", "h1", "-p", "80:80", "httpd"], "delta": "0:00:00.016385", "end": "2021-01-04 03:00:55.403364", "failed_when_result": true, "item": "stderr_lines", "msg": "non-zero return code", "rc": 125, "start": "2021-01-04 03:00:55.386979", "stderr": "/usr/bin/docker-current: Error response from daemon: Conflict. The container name "/h1" is already in use by container bc5cc803a5f4321358992d06097ce271f3a63b8eba19900cfc0d23e321a4e243. You have to remove (or rename) that container to be able to reuse that name..\nSee '/usr/bin/docker-current run --help'.", "stderr_lines": ["/usr/bin/docker-current: Error response from daemon: Conflict. The container name "/h1" is already in use by container bc5cc803a5f4321358992d06097ce271f3a63b8eba19900cfc0d23e321a4e243. You have to remove (or rename) that container to be able to reuse that name..", "See '/usr/bin/docker-current run --help'."], "stdout": "", "stdout_lines": []}"
My playbook is as follows but it didn't work correctly. Sometimes an error in reading dictionary or "Unexpected templating type error occurred on". Can somebody guide me on what should I write?
- name: run a container
vars:
- run_container: docker run -itd --name h1 -p 80:80 httpd
- rm_container: docker stop h1 && docker rm h1
hosts: 192.168.x.x
tasks:
- name: check docker container
block:
- name: run a container httpd
command: "{{run_container}}"
register: rss
with_items:
- "stderr_lines"
failed_when: "'Error' in rss.stderr"
rescue:
- name: iterate over list
debug:
msg: "{{item.value}}"
loop: "{{rss | dict2items}}"
- name: remove the exited container
command: "{{rm_container}}"
register: rs
with_items:
- "{{rss | dict2items}}"
when: item.value is search("The container name .* is already in use")

The conditional check 'user_sdf_exist.rc == 0' failed

I have the following playbook and it fails only on one server and rest all server it is not giving any error
---
- hosts: user_host
tasks:
- name: check sdf user exists
command: grep -Fq "sdf" /etc/passwd
register: user_sdf_exist
ignore_errors: True
changed_when: False
- name: check authorized_keys file exits
stat: path=/home/sdf/.ssh/authorized_keys
register: authorized_keys_file
when: user_sdf_exist.rc == 0
Follwoing is the error that I received
fatal: [xxx.xxx.xxx.xxx]:FAILED! => {"failed": true, "msg": "The conditional check 'user_sdf_exist.rc == 0' failed. The error was: error while evaluating conditional (user_sdf_exist.rc == 0): 'dict object' has no attribute 'rc'\n\nThe error appears to have been in '/home/sdf/bin/configs/ansible/playbooks/roles/ansible_pub_key_for_sdf/tasks/main.yml': line 8, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: check authorized_keys file exits\n ^ here\n"}
But when running the playbook only for this one host playbook passes and returns user_sdf_exist.rc == 0. We have a cron that will run this playbook for every one hour on all the hosts and during this time playbook fails only on this one host.
Output
TASK [debug] *******************************************************************
ok: [xxx.xxx.xxx.xxx] => {
"msg": {
"changed": false,
"cmd": [
"grep",
"-Fq",
"sdf",
"/etc/passwd"
],
"delta": "0:00:00.175056",
"end": "2019-12-11 12:58:50.601619",
"rc": 0,
"start": "2019-12-11 12:58:50.426563",
"stderr": "",
"stdout": "",
"stdout_lines": [],
"warnings": []
}
}
Instead of when: user_sdf_exist.rc == 0
you need to use when: user_sdf_exist is succeeded

Unable to download golang repository by using ansible

I am trying to download a golang package from github. This is how my playbook looks like
- name: Fetch latest gogs repository
shell: "go get -u github.com/gogits/gogs"
become: true
become_user: git
It is throwing me following error:
{
"changed": true,
"cmd": "go get -u github.com/gogits/gogs",
"delta": "0:00:00.002695",
"end": "2017-08-22 10:50:02.984669",
"failed": true,
"invocation": {
"module_args": {
"_raw_params": "go get -u github.com/gogits/gogs",
"_uses_shell": true,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"warn": true
}
},
"rc": 127,
"start": "2017-08-22 10:50:02.981974",
"stderr": "/bin/sh: go: command not found",
"stderr_lines": [
"/bin/sh: go: command not found"
],
"stdout": "",
"stdout_lines": []
}
When I am trying this
- name: Fetch latest gogs repository
shell: "go get -u {{ gogs_repo }}"
environment:
- PATH: $PATH:/usr/local/go/bin:/usr/bin
- GOPATH: "{{gogs_home}}/{{ gogs_project_directory }}/src"
- GOBIN: "{{gogs_home}}/{{ gogs_project_directory }}/bin"
become: true
become_user: git
I got this error
fatal: [atul-ec2]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Shared connection to ec2-13-126-203-235.ap-south-1.compute.amazonaws.com closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n File \"/tmp/ansible_gntmXa/ansible_module_command.py\", line 220, in <module>\r\n main()\r\n File \"/tmp/ansible_gntmXa/ansible_module_command.py\", line 163, in main\r\n os.chdir(chdir)\r\nOSError: [Errno 13] Permission denied: '/home/ec2-user/goprojects/src/src/github.com/gogits/gogs'\r\n",
"msg": "MODULE FAILURE",
"rc": 1
}
Here my variables are
---
go_version: go1.7.linux-amd64.tar.gz
go_url: https://storage.googleapis.com/golang/{{ go_version }}
go_hash: sha256:702ad90f705365227e902b42d91dd1a40e48ca7f67a2f4b2fd052aaa4295cd95
go_project_dir: goprojects
go_home: "{{ ansible_env.HOME }}"
gogs_home: "/home/git"
gogs_project_directory: "git.varadev.com"
gogs_repo: github.com/gogits/gogs
But when i am using following command on my server
which go
I got this
/usr/local/go/bin/go
and when I try manually go get -u github.com/gogits/gogs, it is working fine.
Hope this can help you as a start point:
---
- hosts: all
connection: local
tasks:
- name: check go version
command: go version
register: result
changed_when: no
ignore_errors: true
- set_fact:
go_path: "{{ lookup('env', 'GOPATH') | default(ansible_env.HOME+'/go', true) }}"
when: not result|failed
- name: go get gogs
shell: go get -u github.com/gogits/gogs
environment:
GOPATH: "{{ go_path }}"
register: gogs
when: not result|failed
- debug: var=gogs
Try to run this on your remote server by typing:
ansible-playbook gogs.yml -i localhost,
If that works then just later try remotely.
Normally you don't want to do this since you want to execute this remotely over ssh, but since you had tried so far and are getting some errors, probably by trying locally connection: local could help to debug more in details this issue.
I know this post is too old, but maybe this may help someone.
Ths issue /bin/sh: go: command not found it is because you are missing some configuration when Ansible runs, and probably you need to source the bash profile like this:
- name: Install gogs
shell: "source ~/.bash_profile && github.com/gogits/gogs"
args:
chdir: /home/{{ owner }}
become_user: '{{ owner }}'
That worked for me.

Ansible: Using item(with_items) in changed_when statement

I'm using with_items iterator to execute command: brew services stop {{ item }}.
To handle errors I'd like to use changed_when and use item value in it.
command: brew services stop {{ item }}
register: stop_services
changed_when:
- "'Error: Service `{{ item }}` is not started.' not in stop_services.stderr"
with_items:
- memcached
- kafka
If service is not started, I get following error
failed: [127.0.0.1] (item=memcached) => {"changed": false, "cmd": ["brew", "services", "stop", "memcached"], "delta": "0:00:00.464519", "end": "2016-12-29 18:02:37.795973", "failed": true, "item": "memcached", "rc": 1, "start": "2016-12-29 18:02:37.331454", "stderr": "Error: Service memcached is not started.", "stdout": "", "stdout_lines": [], "warnings": []}
But changed_when statement is ignored.
Is it possible to inject item into changed_when statement?
Ansible version: 2.2
You've got a failing task in the first place. The command module will report failure if the return code from the command was other than zero (in your case "rc": 1) and that's why your changed_when condition is not taken into consideration.
Add the following to prevent failing:
failed_when: false

Resources