How to use python-cloudbuild library to run a build trigger with correctly passing data from SourceRepo?
UPDATE 1:
I have a build trigger set up and I am trying to run that trigger by changing the substitutions and the repo branch
UPDATE 2:
Actual code result:
Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/api_core/grpc_helpers.py", line 67, in error_remapped_callable return callable_(*args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/grpc/_channel.py", line 946, in call return _end_unary_response_blocking(state, call, False, None) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/grpc/_channel.py", line 849, in _end_unary_response_blocking raise _InactiveRpcError(state) grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.INTERNAL
credentials, project_id = google.auth.default()
client = cloudbuild_v1.services.cloud_build.CloudBuildClient()
trigger_id = '2f1erbc4-asdf-1234-qwery-c4bc74d16d62'
repo_source = cloudbuild_v1.RepoSource()
repo_source.branch_name = 'develop'
repo_source.substitutions = {
"_ENVIRONMENT":"dev",
"NAMESPACE":"dev"
}
operation = client.run_build_trigger(
project_id=project_id,
trigger_id=trigger_id,
source=repo_source
)
I am facing the same issue when using the Cloud Build Client Library for Python (google-cloud-build). However, it does work properly when calling the REST API directly, so the library seems to be at cause here. As an alternative, you can achieve the same using the Google API Python client library (google-api-python-client):
from googleapiclient.discovery import build
project_id = "my-project-id"
trigger_id = "00000000-1111-2222-aaaa-bbbbccccdddd"
with build("cloudbuild", "v1") as cloudbuild:
run_build_trigger = cloudbuild.projects().triggers().run(
projectId = project_id,
triggerId = trigger_id,
body = {
"branchName": "dev",
"substitutions": {
"_TEST": "FOO"
}
}
)
run_build_trigger.execute()
Make sure that all substitutions are already declared on the existing trigger.
Related
Here is my piece of web3.py code. I have implemented the smart contract on rinkeby testnet using remix. I am able to call other functions, but when I am calling the transact function I am getting following error.
CODE:
web3 = Web3(Web3.HTTPProvider(url))
web3.middleware_onion.inject(geth_poa_middleware, layer=0)
print(web3.isConnected())
class SendCoin:
def send_coin_on_reps(self, reps):
print(web3.isConnected())
# web3.eth.defaultAccount = web3.eth.accounts[-1]
# INTRACTING WITH REMIX CONTRACT
abi = json.load()
deployed_contract_address = web3.toChecksumAddress('0x40eab3d93EFE536560Ad5802B15EAb56203c3A48')
contract = web3.eth.contract(address = deployed_contract_address, abi = abi)
print(contract)
reward = contract.functions.getReward().call()
print("reward = ", reward)
tx_hash = contract.functions.setReward(reps).transact()
ERROR:
File "/home/sohail/Blockchain/local_ganache_network_web3_app.py", line 48, in send_coin_on_reps
tx_hash = contract.functions.setReward(reps).transact()
File "/home/sohail/anaconda3/lib/python3.9/site-packages/web3/contract.py", line 997, in transact
return transact_with_contract_function(
File "/home/sohail/anaconda3/lib/python3.9/site-packages/web3/contract.py", line 1590, in transact_with_contract_function
txn_hash = web3.eth.send_transaction(transact_transaction)
File "/home/sohail/anaconda3/lib/python3.9/site-packages/web3/eth.py", line 815, in send_transaction
return self._send_transaction(transaction)
File "/home/sohail/anaconda3/lib/python3.9/site-packages/web3/module.py", line 57, in caller
result = w3.manager.request_blocking(method_str,
File "/home/sohail/anaconda3/lib/python3.9/site-packages/web3/manager.py", line 198, in request_blocking
return self.formatted_response(response,
File "/home/sohail/anaconda3/lib/python3.9/site-packages/web3/manager.py", line 171, in formatted_response
raise ValueError(response["error"])
ValueError: {'code': -32601, 'message': 'The method eth_sendTransaction does not exist/is not available'}
It looks to me like you're trying to use a hosted node as if it were a local node. You can read more about the difference in the web3.py docs.
In short: there is no eth_sendTransaction on a hosted node (like Infura, Alchemy, etc), because hosted nodes don't have access to your private keys.
In order to transact(), you need an account funded with ether. Where is the private key for that account? If you have it in python, then you'll want to use the API for signing a contract transaction with local keys.
Otherwise, if the private key is in a local node, like geth, then you'll need to connect to that correctly, probably using an IPC connection. Then a simple transact() invocation should run fine.
I am trying to create an arbitrary CodePipeline action as part of a CDK pipeline implemented in Python. Specifically in this case it's a step function invocation, but I would like to call other types as well. No matter what I do, I keep getting the same error saying it can't find the add_action attribute on the stage object.
jsii.errors.JSIIError: '' object has no attribute 'add_action'
I have tried different variations of the method name, checking the object with dir() (stage is a very opaque InterfaceDynamicProxy object), reading jsii documentation to see if they have a way to list available attributes, but got nowhere.
Does anyone have a working example of jsii interface implementation in Python? Or can you tell what's wrong with the code below?
I am using CDK 1.118.0 with Python 3.9.6 and node.js 16.6.2 on Mac OS X.
from aws_cdk import core, pipelines, aws_codepipeline_actions, aws_codepipeline, aws_stepfunctions
import jsii
#jsii.implements(pipelines.ICodePipelineActionFactory)
class SomeStep(pipelines.Step):
def __init__(self, id_):
super().__init__(id_)
#jsii.member(jsii_name="produceAction")
def produce_action(
self, stage: aws_codepipeline.IStage,
options: pipelines.ProduceActionOptions,
# TODO why are these not passed?
# *,
# action_name, artifacts, pipeline, run_order, scope,
# before_self_mutation=None,
# code_build_defaults=None,
# fallback_artifact=None
) -> pipelines.CodePipelineActionFactoryResult:
stage.add_action(
aws_codepipeline_actions.StepFunctionInvokeAction(
state_machine=aws_stepfunctions.StateMachine.from_state_machine_arn("..."),
action_name="foo",
state_machine_input=aws_codepipeline_actions.StateMachineInput.literal({"foo": "bar"}),
run_order=options["run_order"],
)
)
return pipelines.CodePipelineActionFactoryResult(run_orders_consumed=1)
app = core.App()
stage = core.Stage(app, "stage")
stack = core.Stack(stage, "stack")
pipeline_stack = core.Stack(app, "pipeline-stack")
pipeline = pipelines.CodePipeline(
pipeline_stack,
"pipeline",
synth=pipelines.ShellStep("synth", input=pipelines.CodePipelineSource.git_hub("foo/bar", "main"), commands=["cdk synth"])
)
pipeline.add_wave("wave").add_stage(stage, pre=[SomeStep("some")])
app.synth()
The complete error:
jsii.errors.JavaScriptError:
Error: '' object has no attribute 'add_action'
at KernelHost.completeCallback (/private/var/folders/ln/r1dlp_xj6t57ddclvh7zgl8m0000gp/T/tmpwwmvzicu/lib/program.js:9462:35)
at KernelHost.callbackHandler (/private/var/folders/ln/r1dlp_xj6t57ddclvh7zgl8m0000gp/T/tmpwwmvzicu/lib/program.js:9453:41)
at Step.value (/private/var/folders/ln/r1dlp_xj6t57ddclvh7zgl8m0000gp/T/tmpwwmvzicu/lib/program.js:8323:49)
at CodePipeline.pipelineStagesAndActionsFromGraph (/private/var/folders/ln/r1dlp_xj6t57ddclvh7zgl8m0000gp/T/jsii-kernel-x3iY7A/node_modules/#aws-cdk/pipelines/lib/codepipeline/codepipeline.js:154:48)
at CodePipeline.doBuildPipeline (/private/var/folders/ln/r1dlp_xj6t57ddclvh7zgl8m0000gp/T/jsii-kernel-x3iY7A/node_modules/#aws-cdk/pipelines/lib/codepipeline/codepipeline.js:116:14)
at CodePipeline.buildPipeline (/private/var/folders/ln/r1dlp_xj6t57ddclvh7zgl8m0000gp/T/jsii-kernel-x3iY7A/node_modules/#aws-cdk/pipelines/lib/main/pipeline-base.js:93:14)
at CodePipeline.buildJustInTime (/private/var/folders/ln/r1dlp_xj6t57ddclvh7zgl8m0000gp/T/jsii-kernel-x3iY7A/node_modules/#aws-cdk/pipelines/lib/main/pipeline-base.js:101:18)
at Object.visit (/private/var/folders/ln/r1dlp_xj6t57ddclvh7zgl8m0000gp/T/jsii-kernel-x3iY7A/node_modules/#aws-cdk/pipelines/lib/main/pipeline-base.js:42:57)
at recurse (/private/var/folders/ln/r1dlp_xj6t57ddclvh7zgl8m0000gp/T/jsii-kernel-x3iY7A/node_modules/#aws-cdk/core/lib/private/synthesis.js:86:20)
at recurse (/private/var/folders/ln/r1dlp_xj6t57ddclvh7zgl8m0000gp/T/jsii-kernel-x3iY7A/node_modules/#aws-cdk/core/lib/private/synthesis.js:98:17)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "~/dev/cdk-playground/app.py", line 55, in <module>
app.synth()
File ".../lib/python3.9/site-packages/aws_cdk/core/__init__.py", line 16432, in synth
return typing.cast(aws_cdk.cx_api.CloudAssembly, jsii.invoke(self, "synth", [options]))
File ".../lib/python3.9/site-packages/jsii/_kernel/__init__.py", line 128, in wrapped
return _recursize_dereference(kernel, fn(kernel, *args, **kwargs))
File ".../lib/python3.9/site-packages/jsii/_kernel/__init__.py", line 348, in invoke
return _callback_till_result(self, response, InvokeResponse)
File ".../lib/python3.9/site-packages/jsii/_kernel/__init__.py", line 216, in _callback_till_result
response = kernel.sync_complete(
File ".../lib/python3.9/site-packages/jsii/_kernel/__init__.py", line 386, in sync_complete
return self.provider.sync_complete(
File ".../lib/python3.9/site-packages/jsii/_kernel/providers/process.py", line 382, in sync_complete
resp = self._process.send(_CompleteRequest(complete=request), response_type)
File ".../lib/python3.9/site-packages/jsii/_kernel/providers/process.py", line 326, in send
raise JSIIError(resp.error) from JavaScriptError(resp.stack)
jsii.errors.JSIIError: '' object has no attribute 'add_action'
Subprocess exited with error 1
AWS has resolved the issue in jsii.
https://github.com/aws/jsii/issues/2963
It should be available with CDK 1.121.0.
from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.vision.customvision import prediction
from PIL import Image
endpoint = "https://southcentralus.api.cognitive.microsoft.com/"
project_id = "projectidhere"
prediction_key = "predictionkeyhere"
predict = CustomVisionPredictionClient(prediction_key, endpoint)
with open("c:/users/paul.barbin/pycharmprojects/hw3/TallowTest1.jpg", mode="rb") as image_data:
tallowresult = predict.detect_image(project_id, "test1", image_data)
Python 3.7, and I'm using Azure Custom Vision 3.1? (>azure.cognitiveservices.vision.customvision) (3.1.0)
Note that I've seen the same question on SO but no real solution. The posted answer on the other question says to use the REST API instead.
I believe the error is in the endpoint (as stated in the error), and I've tried a few variants - with the slash, without, using an environment variable, without, I've tried appending various strings to my endpoint but I keep getting the same message. Any help is appreciated.
Full error here:
Traceback (most recent call last):
File "GetError.py", line 15, in <module>
tallowresult = predict.detect_image(project_id, "test1", image_data)
File "C:\Users\paul.barbin\PycharmProjects\hw3\.venv\lib\site-packages\azure\cognitiveservices\vision\customvision\prediction\operations\_custom_vision_
prediction_client_operations.py", line 354, in detect_image
request = self._client.post(url, query_parameters, header_parameters, form_content=form_data_content)
File "C:\Users\paul.barbin\PycharmProjects\hw3\.venv\lib\site-packages\msrest\service_client.py", line 193, in post
request = self._request('POST', url, params, headers, content, form_content)
File "C:\Users\paul.barbin\PycharmProjects\hw3\.venv\lib\site-packages\msrest\service_client.py", line 108, in _request
request = ClientRequest(method, self.format_url(url))
File "C:\Users\paul.barbin\PycharmProjects\hw3\.venv\lib\site-packages\msrest\service_client.py", line 155, in format_url
base = self.config.base_url.format(**kwargs).rstrip('/')
KeyError: 'Endpoint'
CustomVisionPredictionClient takes two required, positional parameters: endpoint and credentials. Endpoint needs to be passed in before credentials, try swapping the order:
predict = CustomVisionPredictionClient(endpoint, prediction_key)
python 3.7
I have a python app for which I run tests:
$ python -m unittest
package code goes like this:
import coreapi
from coreapi import codecs
class myClient():
myApiUrl = None
client = None
def __init__(self, myApiUrl, authenticationToken):
self.myApiUrl = myApiUrl
auth = coreapi.auth.TokenAuthentication(
scheme='Token',
token=authenticationToken
)
decoders = [
codecs.CoreJSONCodec(),
codecs.JSONCodec()
]
self.client = coreapi.Client(auth=auth, decoders=decoders)
def getSomething(self):
....at this point self.client.decoders are present....
schema = self.client.get(self.myApiUrl)
.......blah-blah....
This tests run ends with this error:
ERROR: test_doFirstTest (myclient.tests.SomeTestClass)
Traceback (most recent call last): File "/usr/src/app/myclient/tests.py", line 82, in test_doFirstTest
output = client.test_doFirstTest() File "/usr/src/app/myclient/myClient.py", line 42, in getSomething
schema = self.client.get(self.myApiUrl) File "/opt/conda/lib/python3.7/site-packages/coreapi/client.py", line 136, in get
return transport.transition(link, decoders, force_codec=force_codec) File "/opt/conda/lib/python3.7/site-packages/coreapi/transports/http.py", line 380, in transition
result = _decode_result(response, decoders, force_codec) File "/opt/conda/lib/python3.7/site-packages/coreapi/transports/http.py", line 284, in _decode_result
codec = utils.negotiate_decoder(decoders, content_type) File "/opt/conda/lib/python3.7/site-packages/coreapi/utils.py", line 207, in negotiate_decoder
raise exceptions.NoCodecAvailable(msg) coreapi.exceptions.NoCodecAvailable: Unsupported media in Content-Type header 'text/html'
I realise it's telling me that it received text/html instead of json (maybe an empty string?), but why? I am not doing any request yet, I am doing a preparation step of getting the schema object.
And this is not a connectivity issue, when it can not connect at all it gives different error.
Thanks
Ok this did not have anything to do with coreapi, codex, unittest, requests, or anything I could possible think of. The reason for that error is some docker container involved was exiting silently after starting because another docker container on which the first one depends was not started. So the manifestation just happened to be non-decipherable.
I’m trying to use Python to create EC2 instances but I keep getting these errors.
Here is my code:
#!/usr/bin/env python
import boto3
ec2 = boto3.resource('ec2')
instance = ec2.create_instances(
ImageId='ami-0922553b7b0369273',
MinCount=1,
MaxCount=1,
InstanceType='t2.micro')
print instance[0].id
Here are the errors I'm getting
Traceback (most recent call last):
File "./createinstance.py", line 8, in <module>
InstanceType='t2.micro')
File "/usr/lib/python2.7/site-packages/boto3/resources/factory.py", line 520, in do_action
response = action(self, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/boto3/resources/action.py", line 83, in __call__
response = getattr(parent.meta.client, operation_name)(**params)
File "/usr/lib/python2.7/site-packages/botocore/client.py", line 320, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/usr/lib/python2.7/site-packages/botocore/client.py", line 623, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidAMIID.NotFound) when calling the RunInstances operation: The image id '[ami-0922553b7b0369273]' does not exist
I also get an error when trying to create a key pair
Here's my code for creating the keypair
import boto3
ec2 = boto3.resource('ec2')
# create a file to store the key locally
outfile = open('ec2-keypair.pem','w')
# call the boto ec2 function to create a key pair
key_pair = ec2.create_key_pair(KeyName='ec2-keypair')
# capture the key and store it in a file
KeyPairOut = str(key_pair.key_material)
print(KeyPairOut)
outfile.write(KeyPairOut)
response = ec2.instance-describe()
print response
Here's are the error messages
./createkey.py: line 1: import: command not found
./createkey.py: line 2: syntax error near unexpected token `('
./createkey.py: line 2: `ec2 = boto3.resource('ec2')'
What I am I missing?
For your first script, one of two possibilities could be occurring:
1. The AMI you are referencing by the ID is not available because the key is incorrect or the AMI doesn't exist
2. AMI is unavailable in the region that your machine is setup for
You most likely are running your script from a machine that is not configured for the correct region. If you are running your script locally or on a server that does not have roles configured, and you are using the aws-cli, you can run the aws configure command to configure your access keys and region appropriately. If you are running your instance on a server with roles configured, your server needs to be ran in the correct region, and your roles need to allow access to EC2 AMI's.
For your second question (which in the future should probably be posted separate), your syntax error in your script is a side effect of not following the same format for how you wrote your first script. It is most likely that your python script is not in fact being interpreted as a python script. You should add the shebang at the top of the file and remove the spacing preceding your import boto3 statement.
#!/usr/bin/env python
import boto3
# create a file to store the key locally
outfile = open('ec2-keypair.pem','w')
# call the boto ec2 function to create a key pair
key_pair = ec2.create_key_pair(KeyName='ec2-keypair')
# capture the key and store it in a file
KeyPairOut = str(key_pair.key_material)
print(KeyPairOut)
outfile.write(KeyPairOut)
response = ec2.instance-describe()
print response