While using jenkins API, getting a failure on reconfig_job - python

I am using jenkins rest API to recurse through jobs and then reconfigure this one. All methods work except one. He's is my code :
def get_server_instance():
jenkins_url = 'xxxx'
#server = Jenkins(jenkins_url, username = '', password = '')
# Connect to instance - username and password are optional
server = jenkins.Jenkins(jenkins_url, username = '', password = '')
return server
def get_job_details():
# Refer Example #1 for definition of function 'get_server_instance'
server = get_server_instance()
for job in server.get_jobs_list():
if job == "GithubMigration":
configuration = server.get_job(job).get_config().encode('utf-8')
#server.reconfig_job(job, configuration)
if server.has_job("GithubMigration"):
server.reconfig_job('GithubMigration', config_xml)
It gets my configuration.xml, find the job as well but fails on server.reconfig_job('GithubMigration', config_xml) with the error , AttributeError: 'Jenkins' object has no attribute 'reconfig_job'
when obviously this functions exists in the jenkins rest API and yes I'm importing jenkins, from jenkinsapi.jenkins import Jenkins .
Edit 1 - I uninstalled Jenkinsapi and have only python-jenkins module and now it fails even before saying
AttributeError: 'module' object has no attribute 'Jenkins' for line : AttributeError: 'module' object has no attribute 'Jenkins'
Any ideas?
Edit 2 :
I tries solely python-jenkins API and tried their own example as you see here http://python-jenkins.readthedocs.org/en/latest/example.html
import jenkins
j = jenkins.Jenkins('http://your_url_here', 'username', 'password')
j.get_jobs()
j.create_job('empty', jenkins.EMPTY_CONFIG_XML)
j.disable_job('empty')
j.copy_job('empty', 'empty_copy')
j.enable_job('empty_copy')
j.reconfig_job('empty_copy', jenkins.RECONFIG_XML)
Even this fails at jenkins.Jenkins with attribute error at Jenkins - No module.
I am pretty sure the API is broken.

Your script is probably importing wrong module. You can check it as follows:
import jenkins
print jenkins.__file__
If printed path is other than installation path of jenkins module (eg. C:\Python27_32\lib\site-packages\jenkins\__init__.pyc), then you should check pythonpath:
import sys
print sys.path
Common problem is existence of python script with same name as imported module in current directory, which is at the first place in search path ''.
For more info on import order see module search path

Following #Chemik answer, I realized that the script I wrote was named jenkins.py and it was conflicting with python-jenkins import.
The library isn't broken. Check your script name.

had to add another solution, while running the same command
server = jenkins.Jenkins(jenkins_url, username = '', password = '')
i got the error:
'jenkins' has no attribute 'Jenkins'
my mistake was when installing the package, i installed package "jenkins" and the package i was needed is "python-jenkins".
docs can be found:
python-jenkins docs
so what i had to do is just
pip install python-jenkins

Related

Calling python from django subprocess, mysql not found error

python dbtest1.py ==> work O.K.
dbtest1.py :<br>
import pymysql.connector<br>
dbCon = pymysql.connector.connect(host='...', database='...', user='...', password='...')<br>
cursor = dbCon.cursor()<br>
cursor.execute("INSERT INTO cm_person (name) VALUES ('고길송')")<br>
dbCon.commit()
access from Django using subprocess, Not found error...
views.py include...
def datatest(request):<br>
subprocess.call(['python', 'dbtest3.py'])<br>
return HttpResponse('Call python...')
Error message;
ModuleNotFoundError: No module named 'pymysql'
Did I miss something? or is there any other methods?
Thank you.
If you are using virtual environments, depending how you run your script, 'python' might refer to the system Python. Using sys.executable instead of 'python' might help.
Note that if you are using WSGI, sys.executable is probably not set correctly, so you might want to set it explicitly in your WSGI entry point script.
views.py
def datatest(request):
subprocess.call([sys.executable, "-c", "import dbtest2"])
return HttpResponse('Call python...')

Getting currently playing song with Spotipy gives error: "'Spotify' object has no attribute 'currently_playing'"

I'm programming a script that returns your currently playing song from Spotify.
I read the documentation from Spotify API and everything is working well but I have some problems trying to implement some modules.
For example here https://spotipy.readthedocs.io/en/latest/ said that there's a module called currently_playing() but I get this error:
Traceback (most recent call last):
File "spotify_test.py", line 21, in <module>
current_song = sp.currently_playing()
AttributeError: 'Spotify' object has no attribute 'currently_playing'
By far, this is my code, it works well when I change the scope and the module to obtain the playlists of a user. So the token is not the problem.
import sys
import spotipy
import spotipy.util as util
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print('Usage %s Username ' % (sys.argv[0],))
sys.exit()
scope = 'user-read-currently-playing'
token = spotipy.util.prompt_for_user_token(
username, scope, redirect_uri='http://127.0.0.1/callback')
if token:
sp = spotipy.Spotify(auth=token)
current_song = sp.currently_playing()
else:
print("Can't get token for", username)
print(current_song)
Even if PyPi claims that the version of Spotipy is the latest there, 2.4.4, in fact, it is not. I noticed that after installing Spotipy with pip, its source code is different from the head of the master branch on the GitHub. And the PyPi version doesn't have the currently_playing method.
What worked for me is to uninstall Spotipy by running pip uninstall spotipy and to install it again directly from GitHub:
pip install git+https://github.com/plamere/spotipy.git#master

Integrate airbrake with Python

When I'm trying to integrate python logging with airbrake, I get following errors:
main.py
import pybrake
from config2.config import config
airbrake_handler = None
def filter_airbrake_msgs(notice):
if config.environment in ['production', 'staging']:
return notice
return None
def config_airbrake():
print(config.py_brake)
notifier = pybrake.Notifier(
project_id=config.py_brake.project_id,
project_key=config.py_brake.project_key
)
config_airbrake()
ENV=development python3 main.py
Error :
ERROR pybrake get_git_revision failed: [Errno 2] No such file or directory: '/user/xxx/xxx/xxx/.git/HEAD'
That looks like a log message coming from https://github.com/airbrake/pybrake/blob/master/pybrake/git.py#L12. I see why it is confusing but it is actually harmless and you can ignore it. I've created an issue to remove that log message. And feel free to use Github issues for such questions in future.
Overall pybrake checks if directory stored in context.rootDirectory contains a Git folder. If there is a git folder there it tries to extract some info like git revision, checkout date etc. Otherwise it logs the first error.

Unable to import module 'lambda_function': No module named 'error'

I have a simple Python Code that uses Elasticsearch module "curator" to make snapshots.
I've tested my code locally and it works.
Now I want to run it in an AWS Lambda but I have this error :
Unable to import module 'lambda_function': No module named 'error'
Here is how I proceeded :
I created manually a Lambda and gave it a "AISA-BasicLambdaExecutionRole" role. Then I created my package with my function and the dependencies that I installed with the command :
pip install elasticsearch-curator -t /<path>/myRepository
I zipped the content (not the folder) and uploaded it in my Lambda.
I changed the Handler name to "lambda_function.lambda_handler" (my function's name is "lambda_function.py").
Did I miss something ? This is my first time working with Lambda and Python
I've seen the other questions about this error :
"errorMessage": "Unable to import module 'lambda_function'"
But nothing works for me.
EDIT :
Here is my lambda_function :
from __future__ import print_function
import curator
import time
from curator.exceptions import NoIndices
from elasticsearch import Elasticsearch
def lambda_handler(event, context):
es = Elasticsearch()
index_list = curator.IndexList(es)
index_list.filter_by_regex(kind='prefix', value="logstash-")
Number = 1
try:
while Number <= 3:
Name="snapshotLmbd_n_"+ str(Number) +""
curator.Snapshot(index_list, repository="s3-backup", name= Name , wait_for_completion=True).do_action()
Number += 1
print('Just taking a nap ! will be back soon')
time.sleep(30)
except KeyboardInterrupt:
print('My bad ! I interrupted this')
return
Thank you for your time.
Ok, since you have everything else correct, check for the permissions of the python script.
It must have executable permissions (755)

ansible: local test new module with Error:Module unable to decode valid JSON on stdin. Unable to figure out what parameters were passed

I'm new to Python. This is my first Ansible module in order to delete the SimpleDB domain from ChaosMonkey deletion.
When tested in my local venv with my Mac OS X, it keeps saying
Module unable to decode valid JSON on stdin. Unable to figure out
what parameters were passed.
Here is the code:
#!/usr/bin/python
# Delete SimpleDB Domain
from ansible.module_utils.basic import *
import boto3
def delete_sdb_domain():
fields = dict(
sdb_domain_name=dict(required=True, type='str')
)
module = AnsibleModule(argument_spec=fields)
client = boto3.client('sdb')
response = client.delete_domain(DomainName='module.params['sdb_domain_name']')
module.exit_json(changed = False, meta = response)
def main():
delete_sdb_domain()
if __name__ == '__main__':
main()
And I'm trying to pass in parameters from this file: /tmp/args.json.
and run the following command to make the local test:
$ python ./delete_sdb_domain.py /tmp/args.json
please note I'm using venv test environment on my Mac.
If you find any syntax error in my module, please also point it out.
This is not how you should test your modules.
AnsibleModule expects to have specific JSON as stdin data.
So the closest thing you can try is:
python ./delete_sdb_domain.py < /tmp/args.json
But I bet you have your json file in wrong format (no ANSIBLE_MODULE_ARGS, etc.).
To debug your modules you can use test-module script from Ansible hacking pack:
./hacking/test-module -m delete_sdb_domain.py -a "sdb_domain_name=zzz"

Categories