How to create the custom module in the ansible - module

This is the custom module I have written to get the datetime from the current system. I have put the module in the /usr/share/my_modules folder.
#!/usr/bin/python
import datetime
import json
date = str(datetime.datetime.now())
print(json.dumps({
"time" : date
}))
def main():
module = AnsibleModule(
argument_spec = dict(
state = dict(default='present', choices=['present', 'absent']),
name = dict(required=True),
enabled = dict(required=True, type='bool'),
something = dict(aliases=['whatever'])
)
)
module.exit_json(changed=True, something_else=12345)
module.fail_json(msg="Something fatal happened")
from ansible.module_utils.basic import *
from ansible.module_utils.basic import AnsibleModule
if __name__ == '__main__':
main()
And now When I try to execute it using command ansible local -m timetest
I Am getting this error
127.0.0.1 | FAILED! => {
"failed": true,
"msg": "The module timetest was not found in configured module paths. Additionally, core modules are missing. If this is a checkout, run 'git submodule update --init --recursive' to correct this problem."
}
why it is not executing my custom module ? please help me resolve this issue.

You can create the library directory inside the directory where your playbook exist, your file structure will look like this:
.
|-- playbook.yml
|-- library
`-- your-custom-module.py
Hope that might help you

Have you tried following Ansible test module instructions at http://ansible-docs.readthedocs.io/zh/stable-2.0/rst/developing_modules.html#testing-modules?
git clone git://github.com/ansible/ansible.git --recursive
source ansible/hacking/env-setup
chmod +x ansible/hacking/test-module
ansible/hacking/test-module -m ./timetest.py

Related

from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

modules present in requirements.txt
asgiref==3.5.2
backports.zoneinfo==0.2.1
Django==4.0.5
djangorestframework==3.13.1
djangorestframework-simplejwt==5.2.0
PyJWT==2.5.0
pytz==2022.2.1
sqlparse==0.4.2
configuration in setting.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASS':
['rest_framework_simplejwt.authentication.JWTAuthentication',],
}
After having all proper configuration when i try to import the simplejwt views it is not resolved.
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
Try to mark the Project Directory as source root directory and in pycharm or ide ignore the unresolved error. It will run

Conan Errror : install loop detected in context host .. requires .. which is an ancestor to

I know that this might seem obvious for some of you but I've been digging everywhere for answers with no success. I'm trying to Conan install my own package from my repo but I can't get over this error. It tells me that I have a loop in my requires but my package has no requirement.
I use this recipe for upload with Conan export-pkg :
# Standard library imports
import configparser
import os
import sys
# Related third party imports
import conans
class TlConanFile(conans.ConanFile):
settings = "os", "arch"
def __init__(self, output, runner, display_name="", user=None, channel=None): # pylint: disable=too-many-arguments
super().__init__(output, runner, display_name, user, channel)
if "--build-folder" in sys.argv:
# Conan checks the arguments and fails if the value is missing, the next argument is always the value
build_folder = sys.argv[sys.argv.index("--build-folder") + 1]
self.__class__.exports = os.path.relpath(os.path.join(build_folder, "..", "conanfile.txt"),
os.path.dirname(__file__))
elif "-bf" in sys.argv:
# Conan checks the arguments and fails if the value is missing, the next argument is always the value
build_folder = sys.argv[sys.argv.index("-bf") + 1]
self.__class__.exports = os.path.relpath(os.path.join(build_folder, "..", "conanfile.txt"),
os.path.dirname(__file__))
elif "-pf" in sys.argv:
# Conan checks the arguments and fails if the value is missing, the next argument is always the value
build_folder = sys.argv[sys.argv.index("-pf") + 1]
self.__class__.exports = os.path.relpath(os.path.join(build_folder, "..", "conanfile.txt"),
os.path.dirname(__file__))
elif "--package-folder" in sys.argv:
# Conan checks the arguments and fails if the value is missing, the next argument is always the value
build_folder = sys.argv[sys.argv.index("--package-folder") + 1]
self.__class__.exports = os.path.relpath(os.path.join(build_folder, "..", "conanfile.txt"),
os.path.dirname(__file__))
else:
# Simply assume that we are running the command in the build directory
build_folder = os.getcwd()
self.__class__.exports = os.path.relpath(os.path.join(build_folder, "..", "conanfile.txt"),
os.path.dirname(__file__))
def package(self):
self.copy("*.h", dst="include/aveer", src="output/include/aveer")
self.copy("*.i", dst="include/aveer/swig", src="output/include/aveer/swig")
self.copy("*.so*", dst="lib", src="output/lib", symlinks=True)
self.copy("*.cmake", dst="lib/cmake/aveer", src="output/lib/cmake/aveer")
self.copy("*.so", dst="lib/python3/dist-packages/aveer", src="output/lib/python3/dist-packages/aveer")
self.copy("*", dst="lib/python3/dist-packages/aveer", src="output/lib/python3/dist-packages/aveer")
self.copy("*.yml", dst="share/gnuradio/grc/blocks", src="output/share/gnuradio/grc/blocks")
#self.copy("*", dst="share/gnuradio/grc/blocks", src="share/gnuradio/grc/blocks") doc?
def package_info(self):
self.cpp_info.libs = conans.tools.collect_libs(self)
def requirements(self):
with open("../conanfile.txt") as conanfile_txt:
config = configparser.ConfigParser(allow_no_value=True, delimiters=["\0"])
config.optionxform = str
config.read_file(conanfile_txt)
for requirement in config['requires']:
self.requires(requirement)
to go with this conanfile.py, I also have this conanfile.txt:
[requires]
[generators]
cmake
[options]
that's it for the upload
and I use this conanfile.txt for the install:
[requires]
lib-grplugin/1.0.45#aveer_repo/Release
[generators]
cmake
[options]
[imports]
include/aveer, *.h -> ./output/include/aveer
include/aveer/swig, *.i ->./ output/include/aveer/swig
lib, *.so* -> ./output/lib
lib/cmake/aveer, *.cmake -> ./output/lib/cmake/aveer
lib/python3/dist-packages/aveer, *.so -> ./output/lib/python3/dist-packages/aveer
lib/python3/dist-packages/aveer, *.py -> ./output/lib/python3/dist-packages/aveer
share/gnuradio/grc/blocks, *.yml -> ./output/share/gnuradio/grc/blocks
when I try to run my conan install .. It gives me the following in the prompt:
Picture from the command prompt with the error
I also tried to install another package to test my profile/config and it has worked as intended.
As you can see I'm new here and even newer to conan, so if you need more info that I've not mention here plz let me know.

Bundle npm module 'cheerio' in K6 test

I am trying to create some tests using K6 framework from LoadImpact, but I am struggelig with including external NPM module following the instructions on their documentation site.
On loadImpacts documentations site they include a detailed example on just what I am after, modules that enable me to parse xml from a soap service response. But, I am unable to get this working! Now, I am a total javascript newbie, but I have been coding for many years and would really like to solve this.
The can be found here: https://docs.k6.io/docs/modules#section-npm-modules
can anyone get this working? I need to run this on servers isolated from the Internet, so I am totaly dependent on creating the packages and transfer the required files.
According to the documentation a package is created like this
-- bundle `cheerio` npm module
git clone git#github.com:cheeriojs/cheerio.git
npm install browserify index.js -s cheerio > cheerio.js
My first question: In the folder I am residing when running this command a 'cheerio.js' file is created along with a a 'cheerio' folder and a 'node_modules' folder.
the cheerio.js in my "root" directory only contains the following:
+ cheerio#0.22.0
+ index.js#0.0.3
+ browserify#16.2.3
updated 3 packages and audited 2829 packages in 2.221s
found 0 vulnerabilities
Back to LoadImpacts example on how to reference this package in a k6 javascript:
import cheerio from "./vendor/cheerio.js";
export default function()
{
const res = http.get("https://loadimpact.com/");
const $ = cheerio.load(res.body);
What file is this, and where in the structure generated by browserify can I find it? I have tried to change this to point to 'index.js' in the 'cheerio' folder or cheerio.js found in 'cheerio/lib'. I will then receive a complaint about the first line in cheerio.js which defines a "parse" variable it cannot find:
var parse = require("./parse'),
if I change this to
var parse = require("./parse.js')
it goes on to complain about missing 'htmlparser2' which I can also find in this structure, but it seems like the entire dependency structure is not working.
Can anybody give me some guidance on how to create a browserify package with dependencies for cheerio and how/what I need to copy to my k6 project to make this work like on the loadImpact site.
The k6 docs for this definitely need some clarification, which I'll later do. The vendor folder currently mentioned there isn't something special, the docs are just missing a step to copy the cheerio.js and xml2js.js files that were generated by browserify to a new vendor folder in your k6 project.
For now, I'll try to offer a simplified explanation on how to achieve the same thing in a simpler way:
Create a new empty folder and go to it in a terminal
Run npm install browserify cheerio there (ignore the npm warnings about missing package.json or description)
Run ./node_modules/.bin/browserify ./node_modules/cheerio/ -s cheerio > cheerio.js in that folder
The resulting cheerio.js file in the folder root should be the file you import from the k6 script:
import http from "k6/http";
import cheerio from "./cheerio.js";
export default function () {
const res = http.get("https://loadimpact.com/");
const $ = cheerio.load(res.body);
console.log($('head title').text())
}
That should be it for a single npm library.
And if you need to use multiple npm packages, it might be better to invest some time into bundling them in a single browserified .js file. For example, if you need both the cheerio and the xml2js libraries mentioned in the k6 docs, you can do something like this:
Create a new empty folder
Add something like the following package.json file in it:
{
"name": "k6-npm-libs-demo",
"version": "0.0.1",
"description": "just a simple demo of how to use multiple npm libs in k6",
"main": "npm-main.js",
"dependencies": {},
"devDependencies": {
"browserify": "*",
"cheerio": "*",
"xml2js": "*"
},
"scripts": {
"install": "./node_modules/.bin/browserify npm-main.js -s npmlibs > vendored-libs.js"
},
"author": "",
"license": "ISC"
}
Of course, if you need different libraries than cheerio and xml2js, you need to adjust the devDependencies options.
Add an npm-main.js file like this (again, adjusting for the libraries you want):
exports.xml2js = require('xml2js');
exports.cheerio = require('cheerio');
Open that folder in a terminal and run npm install. That should result in the creation of a vendored-libs.js file in the root of the folder, which you can use in k6 like this:
import http from "k6/http";
import { cheerio, xml2js } from "./vendored-libs.js";
export default function () {
const res = http.get("https://loadimpact.com/");
const $ = cheerio.load(res.body);
console.log($('head title').text())
var xmlString = '<?xml version="1.0" ?>' +
'<items xmlns="http://foo.com">' +
' <item>Foo</item>' +
' <item color="green">Bar</item>' +
'</items>'
xml2js.parseString(xmlString, function (err, result) {
console.log(JSON.stringify(result));
});
}

graphql-tag/loader: Module build failed with GraphQLError: Syntax Error

Weird issue I am facing. Using Vue-CLI3 npm run serve.
Have the following config:
// vue.config.js
module.exports = {
chainWebpack: config => {
// GraphQL Loader
config.module
.rule('graphql')
.test(/\.graphql$/)
.use('graphql-tag/loader')
.loader('graphql-tag/loader')
.end();
}
};
and one single .graphql file:
mutation AddOfficeMutation(
$name: String
$location: String
) {
createOffice(
input: {office: { name: $name, location: $location }}
) {
office {
id
name
location
}
}
}
when running npm run serve, I get the following error:
ERROR Failed to compile with 1 errors 1:11:08 PM
error in ./src/graphql/AddOfficeMutation.graphql
Module build failed (from ./node_modules/graphql-tag/loader.js):
GraphQLError: Syntax Error: Unexpected Name "var"
at syntaxError (/Users/danroc/Dropbox/projects/tal-firebase/client-vue/node_modules/graphql/error/syntaxError.js:24:10)
at unexpected (/Users/danroc/Dropbox/projects/tal-firebase/client-vue/node_modules/graphql/language/parser.js:1490:33)
at parseDefinition (/Users/danroc/Dropbox/projects/tal-firebase/client-vue/node_modules/graphql/language/parser.js:153:9)
at many (/Users/danroc/Dropbox/projects/tal-firebase/client-vue/node_modules/graphql/language/parser.js:1520:16)
at parseDocument (/Users/danroc/Dropbox/projects/tal-firebase/client-vue/node_modules/graphql/language/parser.js:113:18)
at parse (/Users/danroc/Dropbox/projects/tal-firebase/client-vue/node_modules/graphql/language/parser.js:48:10)
at parseDocument (/Users/danroc/Dropbox/projects/tal-firebase/client-vue/node_modules/graphql-tag/src/index.js:129:16)
at gql (/Users/danroc/Dropbox/projects/tal-firebase/client-vue/node_modules/graphql-tag/src/index.js:170:10)
at Object.module.exports (/Users/danroc/Dropbox/projects/tal-firebase/client-vue/node_modules/graphql-tag/loader.js:44:18)
# ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/AddOfficeForm.vue?vue&type=script&lang=js& 29:0-69 59:18-35
# ./src/components/AddOfficeForm.vue?vue&type=script&lang=js&
# ./src/components/AddOfficeForm.vue
# ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/views/AddOfficeView.vue?vue&type=script&lang=js&
# ./src/views/AddOfficeView.vue?vue&type=script&lang=js&
# ./src/views/AddOfficeView.vue
# ./src/router/routes.js
# ./src/router/router-config.js
# ./src/main.js
# multi ./node_modules/#vue/cli-service/node_modules/webpack-dev-server/client?http://192.168.0.99:8080/sockjs-node (webpack)/hot/dev-server.js ./src/main.js
Using:
"graphql": "^14.0.2"
"graphql-tag": "^2.10.0"
I am slowly assuming this might be an error with my Babel or Vue config?
Anyone can shed some light on this?
Thanks!
I faced the same issue and it seemed that having 2 loaders make the crash.
I had installed graphql-tag and webpack-graphql-loader .
Try to uninstall every package that includes apollo or graphql and reinstall using vue cli again. vue add apollo. It worked for me.

How can a README.md file be included in a PyPI module package using setup.py?

I want to include a README.md file with my module package for PyPI such that it can be read by a function in my setup.py. However, it is not obvious to me how to get setup.py and related infrastructure to actually include the README.md file.
I have included a MANIFEST.in file in my package that itself lists README.md and I have set the setuptools.setup argument include_package_data to True but this has not worked.
manifest.in:
junkmodule.py
junkmodule_script.py
LICENSE
MANIFEST.in
README.md
setup.py
setup.py:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import pypandoc
import setuptools
def main():
setuptools.setup(
name = "junkmodule",
version = "2017.01.13.1416",
description = "junk testing module",
long_description = pypandoc.convert("README.md", "rst"),
url = "https://github.com/user/junkmodule",
author = "LRH",
author_email = "lhr#psern.ch",
license = "GPLv3",
include_package_data = True,
py_modules = [
"junkmodule"
],
install_requires = [
"numpy"
],
scripts = [
"junkmodule_script.py"
],
entry_points = """
[console_scripts]
junkmodule = junkmodule:junkmodule
"""
)
if __name__ == "__main__":
main()
The commands I use to register and upload the module to PyPI are as follows:
python setup.py register -r https://pypi.python.org/pypi
python setup.py sdist upload -r https://pypi.python.org/pypi
I'm using this in my modules, try:
import pypandoc
try:
description=pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
description=open('README.md').read()