Implementation error for type bool when writing custom Ansible module - ansible

I'm trying to write a custom module in Ansible 2.3 to use in my playbook. The details of it has been abstracted to run a minimal date command below, but I'm developing a much complicated example.
[dev#foobar Gist]$ tree ansible_version_err/
ansible_version_err/
├── dev_command.yml
└── library
└── dev_command.py
The contents of the library file is using the ansible.module package to implement the custom command.
#!/usr/bin/python
from ansible.module_utils.basic import *
from subprocess import Popen, PIPE
import time
if __name__ == '__main__':
module = AnsibleModule(
argument_spec={
'command': { 'type':'str', 'required': True },
'print_elapsed': { 'type':bool, 'required': False },
'print_time': { 'type':bool, 'required': False } } )
stdout = None
stderr = None
rc = None
try:
time_start = time.time()
proc = Popen( module.params['command'], shell = True)
stdout, stderr = proc.communicate()
time_end = time.time()
rc = proc.returncode
if rc != 0:
raise Exception("error while obtaining date")
time_elapsed = time_end - time_start
if 'print_elapsed' in module.params and module.params['print_elapsed']:
stdout = stdout + "\nelapsed time: " + str(time_elapsed)
if 'print_time' in module.params and module.params['print_time']:
stdout = stderr + "\ntime: " + time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time_start))
module.exit_json( changed = False, stdout = stdout, stderr = stderr, rc = rc, time_elapsed = time_elapsed )
except Exception:
pass
and the .yml file using this dev_command is called as
---
- hosts: localhost
gather_facts: no
tasks:
- name: testing a custom command
vars:
print_stdout: True
dev_command: command="{{cmd}}" print_elapsed=True print_time=True
I'm just calling the cmd with date which will go ahead and run the date command.
ansible-playbook dev_command.yml -vvv -e "cmd=date"
While I expect this work on Ansible 2.3, it is throwing me an error as
fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
"invocation": {
"module_args": {
"command": "date",
"print_elapsed": "True",
"print_time": "True"
}
},
"msg": "implementation error: unknown type <type 'bool'> requested for print_time"
}
This error is not seen in v2.6. Why is this happening? Is this a known Ansible feature bug that can only be resolved by moving to a newer version. Version details
$ ansible --version
ansible 2.3.0.0
config file = /etc/ansible/ansible.cfg
configured module search path = Default w/o overrides
python version = 2.7.5 (default, Nov 6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]

Q: "On Ansible 2.3, it is throwing me an error ... This error is not seen in v2.6. Why is this happening? Is this a known Ansible feature bug that can only be resolved by moving to a newer version?"
A: Yes. It's necessary to move to a maintained version. Even if it was a known problem it wouldn't be fixed anymore. Ansible Release cycle says:
"Ansible has a graduated maintenance structure that extends to three major releases ... we strongly encourage you to upgrade as soon as possible ..."
The latest Ansible version is 2.9 at the moment. The last maintained version is 2.7 at the moment.
FWIW. The command
$ grep -r type /scratch/ansible/lib/ansible/modules/ | grep bool | grep defaul
shows all modules declare the type Boolean with quotation
type='bool'
or
'type': 'bool'

Related

Ansible WinRM: Unknown failure when polling update result - attempting to cancel task: pop from empty list

Linux Ubuntu 18
Ansile 2.9.27
Python 3.6
pywinrm 0.4.2
Remote host: Microsoft Windows 10 Enterprise
How to fix the error pop from empty list ?
Ansible playbook code:
- win_updates:
category_names:
- CriticalUpdates
reboot: no
reboot_timeout: 1000
Ansible console log showing Warning:
<1.2.3.4> Running win_updates - round 1
<1.2.3.4> Starting update task
Using module file /somewhere/collections/ansible_collections/ansible/windows/plugins/modules/win_updates.ps1
Pipelining is enabled.
EXEC (via pipeline wrapper)
<1.2.3.4> Starting polling for update results
EXEC (via pipeline wrapper)
[WARNING]: Unknown failure when polling update result - attempting to cancel task: pop from empty list
EXEC (via pipeline wrapper)
EXEC (via pipeline wrapper)
Error printed to console:
IndexError: pop from empty list
fatal: [1.2.3.4]: FAILED! => {
"changed": false,
"failed_update_count": 0,
"filtered_updates": {},
"found_update_count": 0,
"installed_update_count": 0,
"invocation": {
"module_args": {
"accept_list": null,
"category_names": [
"CriticalUpdates"
],
"log_path": null,
"reboot": false,
"reboot_timeout": 1000,
"reject_list": null,
"server_selection": "default",
"skip_optional": false,
"state": "installed",
"use_scheduled_task": false
}
},
"msg": "pop from empty list",
"updates": {}
}
Potential workaround
The code fails in win_updates.py --> offset = int(lines.pop(-1)) , when lines is empty. Is lines = stdout.splitlines() expected to return something always? Otherwise, we can just ignore the pop(-1) when it's empty.

GPG not working with python 3.8 but ok with 3.6

I have just started dabbling with Python and I’m stuck with my first project
I need help in trying to make some sense out gpg. I have been struggle with trying to get gpg to work with python 3.8.1. If run the code in Thonny Python 3.6.9 in run just fine.
The version is gpg (GnuPG) 2.2.4 libgcrypt 1.8.1
Home directory : /home/bob/.gnupg
gnupg : /usr/local/lib/python3.8/site-packages/gnupg
using Python 3.6.9 works just fine
#!/usr/bin/python3
from pathlib import Path
import gnupg
# My gpg keys home directory.
#gpg = gnupg.GPG(homedir='/home/bob/.gnupg')
gpg = gnupg.GPG(gnupghome='/home/bob/.gnupg')
local_path = Path("/home/bob")
src_dir = ("/home/bob/Tbox/Channels2.csv")
with open(src_dir, 'rb') as afile:
# text = afile.read()
status = gpg.encrypt_file(afile,
['bobh#gunas.co.uk'],
output='/home/bob/Tbox/Channels2.csv.gpg')
print('ok: ', status.ok)
print('status: ', status.status)
print('stderr: ', status.stderr)
SHELL OUTPUT
ok: True
status: encryption ok
stderr: [GNUPG:] KEY_CONSIDERED 4678A2C439E752DA3DAE2EBA7357BB95381CD73 0
[GNUPG:] KEY_CONSIDERED 4678A2C439E752DA3DAE2EBA7357BB95381CD73 0
[GNUPG:] ENCRYPTION_COMPLIANCE_MODE 23
[GNUPG:] BEGIN_ENCRYPTION 2 9
[GNUPG:] END_ENCRYPTION
however if I run the code in Thonny Python 3.8.1 I not working withy error message in Shell
#!/usr/bin/python3
from pathlib import Path
import gnupg
# My gpg keys home directory.
gpg = gnupg.GPG(homedir='/home/bob/.gnupg')
#gpg = gnupg.GPG(gnupghome='/home/bob/.gnupg')
local_path = Path("/home/bob")
backup_dir = Path("/home/bob/Tbox/tbackup-test")
src_dir = ("/home/bob/Tbox/Channels2.csv")
with open(src_dir, 'rb') as afile:
text = afile.read()
# status = gpg.encrypt_file(text,
status = gpg.encrypt(afile,
['bobh#gunas.co.uk'],
output='/home/bob/Tbox/Channels2.csv.gpg')
print('ok: ', status.ok)
print('status: ', status.status)
print('stderr: ', status.stderr)
SHELL OUTPUT
ok: False
status: None
stderr: gpg: Sorry, no terminal at all requested - can't get input
I have tried add the line no-tty to the gpg.conf file but this did not help.
I have tried with some example of the net but with on joy, one problem I have found is to do with gpg and the word Context like c = gpg.core.Context(armor=True) error AttributeError: 'GPG' object has no attribute 'core'.
In the second example, instead of:
status = gpg.encrypt(afile,
you probably need:
status = gpg.encrypt(text,
Basically you need to decide if you are encrypting a file, or the contents of a file (that you're reading in variable 'text'), and then you either use gpg.encrypt or gpg.encrypt_file accordingly.

'No such file or directory' error when using buildGoPackage in nix

I'm trying to build the hasura cli: https://github.com/hasura/graphql-engine/tree/master/cli with the following code (deps derived from dep2nix):
{ buildGoPackage, fetchFromGitHub }:
buildGoPackage rec {
version = "1.0.0-beta.2";
name = "hasura-${version}";
goPackagePath = "github.com/hasura/graphql-engine";
subPackages = [ "cli" ];
src = fetchFromGitHub {
owner = "hasura";
repo = "graphql-engine";
rev = "v${version}";
sha256 = "1b40s41idkp1nyb9ygxgsvrwv8rsll6dnwrifpn25bvnfk8idafr";
};
goDeps = ./deps.nix;
}
but I get the following errors after the post-installation fixup step:
find: '/nix/store/gkck68cm2z9k1qxgmh350pq3kwsbyn8q-hasura-cli-1.0.0-beta.2': No such file or directory.
What am I doing wrong here? For reference, I'm on macOS and using home-manager.
For anyone still wondering:
There are a couple of things to consider:
dep has been deprecated in favor of go modules
This is also reflected in Nix, as buildGoPackage is now legacy and moved to buildGoModule
There is already a hasura-cli package in nixpkgs. You can just use it with nix-shell -p hasura-cli

Odoo 11 No Module Found

Hi I am new to odoo and linux ubuntu 16.04 LTS, I had set up the ubuntu desktop on an oracle vm virtualbox, I have also installed the necessary repository and apt for odoo11, postgresql, python3 and pycharm.
My odoo11 is already working fine and I am able to install and run existing applications, however I have tried to generate a scaffold to develop a module of my own, and I have followed guides and documentations.
My odoo.conf has these options
[options]
; This is the password that allows database operations:
; admin_passwd = admin
db_host = False
db_port = False
db_user = odoo
db_password = False
logfile = /var/log/odoo/odoo-server.log
addons_path = /opt/odoo/odoo/addons,/home/mtsoftware/Documents/projects/tutorial/addons
while my manifest.py has these option
# -*- coding: utf-8 -*-
{
'name': "myfirstModel",
'summary': """
Short (1 phrase/line) summary of the module's purpose, used as
subtitle on modules listing or apps.openerp.com""",
'description': """
Long description of module's purpose
""",
'author': "My Company",
'website': "http://www.yourcompany.com",
# Categories can be used to filter modules in modules listing
# Check https://github.com/odoo/odoo/blob/master/odoo/addons/base/module/module_data.xml
# for the full list
'category': 'Uncategorized',
'version': '0.1',
# any module necessary for this one to work correctly
'depends': ['base'],
# always loaded
'data': [
# 'security/ir.model.access.csv',
'views/customer.xml',
],
# only loaded in demonstration mode
'demo': [
'demo/demo.xml',
],
}
Upon trying to search for "myfirstModel" in my module list # odoo11 application page, it returns a "No module found!"
Any one can help me?

How do i know the service status in ansible?

In my ansible coding i want to know the status of the service like service httpd status (service is runngin or not) the result would be store in to variable. Using that status i will use some other code in ansible.
I am using ansible service module there is no option for status. If i use the shell module i got this warning
[WARNING]: Consider using service module rather than running service
so is it any other module doing to get service status?
No, there is no standard module to get services' statuses.
But you can suppress warning for specific command task if you know what are you doing:
- command: service httpd status
args:
warn: false
I've posted a quick note about this trick a while ago.
You can use the service_facts module.
For example, say I want to see the status of Apache.
- name: Check for apache status
service_facts:
- debug:
var: ansible_facts.services.apache2.state
The output is:
ok: [192.168.blah.blah] => {
"ansible_facts.services.apache2.state": "running"
}
If you would like to see all of them, you can do that by just going two levels up in the array:
var: ansible_facts.services
The output will list all the services, and will look like this (truncated for the sake of brevity):
"apache2": {
"name": "apache2",
"source": "sysv",
"state": "running"
},
"apache2.service": {
"name": "apache2.service",
"source": "systemd",
"state": "running"
},
"apparmor": {
"name": "apparmor",
"source": "sysv",
"state": "running"
},
etc,
etc
I am using Ansible 2.7. Here are the docs for that module: Click here
here is an example of starting a service and then checking status using service facts, in my example you have to register the variable then output it using debug var and pointing to the correct format in the json chain resulting output:
## perform start service for alertmanager
- name: Start service alertmanager if not started
become: yes
service:
name: alertmanager
state: started
## check to see the state of the alertmanager service status
- name: Check status of alertmanager service
service_facts:
register: service_state
- debug:
var: service_state.ansible_facts.services["alertmanager.service"].state
Hopefully service: allow user to query service status #3316 will be merged into the core module soon.
You can patch it by hand using this diff to system/service.py
Here's my diff using ansible 2.2.0.0. I've run this on my mac/homebrew install and it works for me.
This is the file that I edited: /usr/local/Cellar/ansible/2.2.0.0_2/libexec/lib/python2.7/site-packages/ansible/modules/core/system/service.py
## -36,11 +36,12 ##
- Name of the service.
state:
required: false
- choices: [ started, stopped, restarted, reloaded ]
+ choices: [ started, stopped, status, restarted, reloaded ]
description:
- C(started)/C(stopped) are idempotent actions that will not run
- commands unless necessary. C(restarted) will always bounce the
- service. C(reloaded) will always reload. B(At least one of state
+ commands unless necessary. C(status) would report the status of
+ the service C(restarted) will always bounce the service.
+ C(reloaded) will always reload. B(At least one of state
and enabled are required.)
sleep:
required: false
## -1455,7 +1456,7 ##
module = AnsibleModule(
argument_spec = dict(
name = dict(required=True),
- state = dict(choices=['running', 'started', 'stopped', 'restarted', 'reloaded']),
+ state = dict(choices=['running', 'started', 'stopped', 'status', 'restarted', 'reloaded']),
sleep = dict(required=False, type='int', default=None),
pattern = dict(required=False, default=None),
enabled = dict(type='bool'),
## -1501,6 +1502,9 ##
else:
service.get_service_status()
+ if module.params['state'] == 'status':
+ module.exit_json(state=service.running)
+
# Calculate if request will change service state
service.check_service_changed()

Resources