My problem is best described by the following script:
import boto
boto.__version__
# OUT: '2.19.0'
from boto.ec2.connection import EC2Connection
ec2 = EC2Connection(**creds)
regions = ec2.get_all_regions()
from boto.sqs.connection import SQSConnection
regions[0]
# OUT: RegionInfo:eu-west-1
sqs = SQSConnection(region=regions[0], **creds)
sqs.get_all_queues()
# OUT: Traceback (most recent call last):
# OUT: File "<input>", line 1, in <module>
# OUT: File "/opt/zenoss/lib/python2.7/site-packages/boto/sqs/connection.py", line 338, in get_all_queues
# OUT: return self.get_list('ListQueues', params, [('QueueUrl', Queue)])
# OUT: File "/opt/zenoss/lib/python2.7/site-packages/boto/connection.py", line 1119, in get_list
# OUT: raise self.ResponseError(response.status, response.reason, body)
# OUT: SQSError: SQSError: 400 Bad Request
# OUT: <?xml version="1.0" encoding="UTF-8"?>
# OUT: <Response><Errors><Error><Code>NoSuchVersion</Code><Message>The requested version (2012-11-05) of service AmazonEC2 does not exist</Message></Error></Errors><RequestID>1600907e-6780-46f5-b5e6-e647a660abf8</RequestID></Response>
I could not find documentation for AWS or boto about meaning of this error, and how to fix it. Is that a bug of boto?
The problem with the above code is that the get_all_regions() call from the EC2 module returns a list of RegionInfo objects consisting of a region name and a region endpoint. But the endpoint is for the EC2 service, not SQS. So, if you pass that RegionInfo into the SQSConnection constructor it will end up trying to make SQS requests against an EC2 endpoint which results in the NoSuchVersion error.
Here's how I would do this:
import boto.sqs
sqs = boto.sqs.connect_to_region('eu-west-1')
sqs.get_all_queues()
Similarly, if you need an EC2 connection:
import boto.ec2
ec2 = boto.ec2.connect_to_region('eu-west-1')
Related
I am working on a script that accesses details about an Azure Virtual Machine currently. This is the code that I have so far:
"""
Instantiate the ComputeManagementClient with the appropriate credentials.
#return ComputeManagementClient object
"""
def get_access_to_virtual_machine():
subscription_id = key.SUBSCRIPTION_ID
credentials = DefaultAzureCredential(authority = AzureAuthorityHosts.AZURE_GOVERNMENT,
exclude_environment_credential = True,
exclude_managed_identity_credential = True,
exclude_shared_token_cache_credential = True)
client = KeyClient(vault_url = key.VAULT_URL, credential = credentials)
compute_client = ComputeManagementClient(credentials, subscription_id)
return compute_client
"""
Check to see if Azure Virtual Machine exists and the state of the virtual machine.
"""
def get_azure_vm(resource_group_name, virtual_machine_name):
compute_client = get_access_to_virtual_machine()
vm_data = compute_client.virtual_machines.get(resource_group_name,
virtual_machine_name,
expand = 'instanceView')
return vm_data
When trying to run get_azure_vm(key.RESOURCE_GROUP, key.VIRTUAL_MACHINE_NAME) which I am certain does have the correct credentials, I get the following error output (note that I replaced the actual subscription ID with 'xxxx' for now):
Traceback (most recent call last):
File "/Users/shilpakancharla/Documents/function_app/WeedsMediaUploadTrigger/event_process.py", line 62, in <module>
vm_data = get_azure_vm(key.RESOURCE_GROUP, key.VIRTUAL_MACHINE_NAME)
File "<decorator-gen-2>", line 2, in get_azure_vm
File "/usr/local/lib/python3.9/site-packages/retry/api.py", line 73, in retry_decorator
return __retry_internal(partial(f, *args, **kwargs), exceptions, tries, delay, max_delay, backoff, jitter,
File "/usr/local/lib/python3.9/site-packages/retry/api.py", line 33, in __retry_internal
return f()
File "/Users/shilpakancharla/Documents/function_app/WeedsMediaUploadTrigger/event_process.py", line 55, in get_azure_vm
vm_data = compute_client.virtual_machines.get(resource_group_name,
File "/usr/local/lib/python3.9/site-packages/azure/mgmt/compute/v2019_12_01/operations/_virtual_machines_operations.py", line 641, in get
map_error(status_code=response.status_code, response=response, error_map=error_map)
File "/usr/local/lib/python3.9/site-packages/azure/core/exceptions.py", line 102, in map_error
raise error
azure.core.exceptions.ResourceNotFoundError: (SubscriptionNotFound) The subscription 'xxxx' could not be found.
Code: SubscriptionNotFound
Message: The subscription 'xxxx' could not be found.
I am using the beta preview version of azure.mgmt.compute which was installed with pip install azure-mgmt-compute=17.0.0b1. Note that I am also using an Azure Government account. Is there a way to solve this error? I have also tried using ServicePrincipalCredentials and get_azure_credentials() but ran into different errors - I was recommended to use DefaultAzureCredentials and the key vault by a coworker.
There is no problem with the code and it works fine on my side. And the error message shows the reason:
azure.core.exceptions.ResourceNotFoundError: (SubscriptionNotFound)
The subscription 'xxxx' could not be found. Code: SubscriptionNotFound
Message: The subscription 'xxxx' could not be found.
It seems you run the python code in your local machine. I recommend you log in with the Azure CLI first and then check if the subscription id that you used in your python code is right.
I'm using the python-twitter (not tweepy) module in my application.
I have a script set up (maketweet.py) that, when I run it from bash / console, works successfully (i.e. it makes a tweet).
The problem I'm having is that when I run the same script as a scheduled task, I get an error:
Traceback (most recent call last):
File "/home/dir1/dir2/proj/maketweet.py", line 21, in <module>
api = create_api()
File "/home/dir1/dir2/proj/config.py", line 31, in create_api
if api.VerifyCredentials():
File "/home/dir1/.local/lib/python3.8/site-packages/twitter/api.py", line 4699, in VerifyCredentials
resp = self._RequestUrl(url, 'GET', data)
File "/home/dir1/.local/lib/python3.8/site-packages/twitter/api.py", line 4959, in _RequestUrl
raise TwitterError("The twitter.Api instance must be authenticated.")
twitter.error.TwitterError: The twitter.Api instance must be authenticated.
The other problem I'm having is that I can't conceive why it would make a difference that I'm using a scheduled task, rather than running the file directly from bash. Here are the contents of config.py:
#!/usr/bin/python3.8
import twitter
import os
import logging
from dotenv import load_dotenv
logger = logging.getLogger()
# project folder is one level up from file location
project_folder = pathlib.Path(__file__).parent.absolute()
load_dotenv(os.path.join(project_folder, '.env'))
# Authenticate to Twitter and create API object
TWITTER_CONSUMER_API_KEY = os.getenv("TWITTER_CONSUMER_API_KEY")
TWITTER_CONSUMER_API_SECRET = os.getenv("TWITTER_CONSUMER_API_SECRET")
TWITTER_ACCESS_TOKEN = os.getenv("TWITTER_ACCESS_TOKEN")
TWITTER_ACCESS_SECRET = os.getenv("TWITTER_ACCESS_SECRET")
def create_api():
# Create API object
api = twitter.Api(
access_token_key = TWITTER_ACCESS_TOKEN,
access_token_secret = TWITTER_ACCESS_SECRET,
consumer_key = TWITTER_CONSUMER_API_KEY,
consumer_secret = TWITTER_CONSUMER_API_SECRET,
sleep_on_rate_limit=True)
# test API object
if api.VerifyCredentials():
pass
else:
logger.error("Error creating API", exc_info=True)
raise Exception("Twitter user authentication error")
logger.info("API created")
return api
Obviously there's an error in creating the API. I imagine this has something to do with the environment variables and how they are accessed through scheduled tasks vs. bash. Just really not sure how to figure this one out...
I am trying to use my own configuration file with pyngrok but I don't understand why it does not detect it, my project needs to be run forcefully with sudo, therefore ngrok does not detect the configuration file in the root home directory for some users, it is that's why I want to mount my own configuration file in my project directory, here is my code:
from pyngrok import ngrok, conf
import os
from pathlib import Path
import re
def ngrok_start ():
file = Path (".config/ngrok.yml")
if file.exists():
os.system("kill -9 $(pgrep ngrok)")
ngrok.DEFAULT_CONFIG_PATH = ".config/ngrok.yml"
ngrok.connect(443, "tcp")
while True:
ngrok_tunnels = ngrok.get_tunnels()
url = ngrok_tunnels[0].public_url
if re.match ("tcp://[0-9]*.tcp.ngrok.io:[0-9]*", url) is not None:
print ("Ngrok TCP:" + url)
break
With my code I get the following error:
Traceback (most recent call last):
File "ngrok.py", line 27, in <module>
ngrok_start ()
File "ngrok.py", line 20, in ngrok_start
ngrok.connect (443, "tcp")
File "/usr/local/lib/python2.7/dist-packages/pyngrok/ngrok.py", line 181, in connect
timeout = pyngrok_config.request_timeout))
File "/usr/local/lib/python2.7/dist-packages/pyngrok/ngrok.py", line 321, in api_request
status_code, e.msg, e.hdrs, response_data)
pyngrok.exception.PyngrokNgrokHTTPError: ngrok client exception, API returned 502: {"error_code": 103, "status_code": 502, "msg": "failed to start tunnel", "details": {"err": "TCP tunnels are only available after you sign up. \ nSign up at: https://ngrok.com/signup\n\nIf you have already signed up, make sure your authtoken is installed. \ nYour authtoken is available on your dashboard: https: //dashboard.ngrok.com/auth/your-authtoken\r\n\r\nERR_NGROK_302\r\n "}}
No handlers could be found for logger "pyngrok.process"
My script is in the lib folder and my configuration file in .config/ngrok.yml, in which I have my token but I can't detect it, I hope you can support me, thanks.
imagen
Per the docs, the DEFAULT_CONFIG_PATH variable is in the conf module, not the ngrok module. So change ngrok.DEFAULT_CONFIG_PATH = to conf.get_default().config_path = .
Hi everyone I am having an issue with pub sub that is driving me nuts. Basically I have a service account with admin priivs for pubsub but I can't get any thing to work and am getting the following error:
ERROR:root:AuthMetadataPluginCallback "" raised exception!
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/grpc/_plugin_wrapping.py", line 77, in call
callback_state, callback))
File "/usr/local/lib/python2.7/dist-packages/google/auth/transport/grpc.py", line 77, in call
callback(self._get_authorization_headers(context), None)
File "/usr/local/lib/python2.7/dist-packages/google/auth/transport/grpc.py", line 61, in _get_authorization_headers
self._credentials.before_request(
AttributeError: 'str' object has no attribute 'before_request'
Code is super simple
from google.cloud import pubsub
credentials = '/home/airflow/Desktop/test/config/test.json'
publisher = pubsub.PublisherClient(credentials=credentials)
topic_path = publisher.topic_path("test-proj", "test")
for n in range(1, 2):
data = u'Message number {}'.format(n)
# Data must be a bytestring
data = data.encode('utf-8')
test = publisher.publish(topic_path, data=data).result()
print(test, "s")
Amy help would be really appreciated as the error message doesn't make much sense to me. Thanks
The credentials argument for PublisherClient is not a string. It is a google.auth.credentials.Credentials object. The google-auth-guide indicates how to create it:
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
'/home/airflow/Desktop/test/config/test.json')
I've come back to Python after a couple of years of not having used it. I'm testing the Imgur Python library. After a fresh install of Python 2.7.12, I did a quick pip install of ImgurPython, then dragged a small folder of the sample scripts to my desktop for testing.
The auth.py sample script begins with a function that includes:
# Get client ID and secret from auth.ini
config = get_config()
config.read('auth.ini')
client_id = config.get('credentials', 'client_id')
client_secret = config.get('credentials', 'client_secret')
client = ImgurClient(client_id, client_secret)
The auth.ini file is in the same folder as the auth.py folder, and contains my client ID and secret. However, when running the script, I get:
C:\Windows\system32>python C:\Users\[REDACTED]\Desktop\imgtest\auth.py
Traceback (most recent call last):
File "C:\Users\[REDACTED]\Desktop\imgtest\auth.py", line 41, in <module>
authenticate()
File "C:\Users\[REDACTED]\Desktop\imgtest\auth.py", line 16, in authenticate
client_id = config.get('credentials', 'client_id')
File "J:\Python27\lib\ConfigParser.py", line 607, in get
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'credentials'
Removing the need to get the credentials from the auth.ini file and placing them directly in the Python script has it run with no error.
I'm sure I'm overlooking something simple, but I could use some assistance in figuring out why python won't read the auth.ini file.
You may have a bad format of auth.ini file. In my python 2.7, the extraction works totally fine with ConfigParser:
$ cat auth.ini
[credentials]
client_id=foo
client_secret=bar
In my Ipython:
In [1]: import ConfigParser
In [2]: config = ConfigParser.ConfigParser()
In [3]: config.read('auth.ini')
Out[3]: ['auth.ini']
In [4]: client_id = config.get('credentials', 'client_id')
In [5]: client_secret = config.get('credentials', 'client_secret')
In [6]: client_id
Out[6]: 'foo'
In [7]: client_secret
Out[7]: 'bar'