I am trying to auto tag instances and following one blog. But I am getting key error for everything from user_email i.e, json payload key error, actor key error. I am following this blog https://blog.doit-intl.com/automatically-label-google-cloud-compute-engine-instances-and-disks-upon-creation-5d1245f361c1
I think there might be problem at pubsub/stackdriver end. Is there any way to work it out
def hello_pubsub(event, context):
# parse the pubsub event
pubsub_message = json.loads(base64.b64decode(event['data']).decode('utf-8'))
# pubsub variables
user_email = pubsub_message['jsonPayload']['actor']['user'].replace('#', '_', ).replace('.', '-')
instance_zone = pubsub_message['jsonPayload']['operation']['zone']
instance_name = pubsub_message['jsonPayload']['resource']['name']
project_id = pubsub_message['resource']['labels']['project_id']
logging.info(f'new instance created, going to tag instance {instance_name}')
# tag the instance
instance_tag = tag_instance(instance_name, project_id, instance_zone, user_email)
# if instance tag was successful and the instance volume list exists
if instance_tag and instance_tag['instance_disks_list']:
disks_list = instance_tag['instance_disks_list']
# tag volumes
disks_tag = tag_disks(disks_list, project_id, instance_zone, instance_name, user_email)
if disks_tag:
return True
Related
My goal is to create a pdf using WeasyPrint and add it the the payload sent to the Docusign Api when requesting an envelope to be created.
Here are my steps:
generate the a pdf with WeasyPrint and return a based64 string
def generate_envelope_document(document_name: str, context: dict):
content = render_to_string(f"insurance_contracts/{document_name}.html",
context=context)
css = find(f"insurance_contracts/{document_name}.css")
doc = HTML(string=content, media_type="screen").write_pdf(stylesheets=[css],
zoom=0.8)
return base64.b64encode(doc).decode("utf-8")
create my envelope definition:
def create_envelope_definition(envelope_data: dict, context: dict, custom_fields: dict = None):
mandate = Document(
document_base64=generate_envelope_document("name1", context),
name="name1",
file_extension="pdf",
document_id=1,
)
conditions = Document(
document_base64=generate_envelope_document("name2", context),
name="name2",
file_extension="pdf",
document_id=2,
)
signer = Signer(
email=envelope_data["signer_email"],
name=envelope_data["signer_name"],
recipient_id="1",
routing_order="1",
)
signer.tabs = Tabs(
sign_here_tabs=[
SignHere(
anchor_string="Sign",
anchor_units="pixels",
anchor_y_offset="50",
anchor_x_offset_metadata="50",
)
]
)
envelope_definition = EnvelopeDefinition(
status="sent", documents=[mandate, conditions], recipients=Recipients(signers=[signer])
)
if custom_fields:
envelope_definition.custom_fields = CustomFields(
text_custom_fields=[
TextCustomField(name=field_name, value=field_value, required=False)
for field_name, field_value in enumerate(custom_fields)
]
)
return envelope_definition
create a Docusign Api object:
def get_envelopes_api_client():
"""
Create the docusign api client object
Return EnvelopesApi object
"""
api_client = ApiClient()
api_client.host = settings.DOCUSIGN_BASE_PATH
api_client.set_default_header("Authorization", "Bearer " + get_access_token())
envelope_api = EnvelopesApi(api_client)
return envelope_api
create and send the Docusign envelope:
envelope_api = get_envelopes_api_client()
try:
envelope = envelope_api.create_envelope(
settings.DOCUSIGN_ACCOUNT_ID, envelope_definition=envelope_definition
)
except ApiException as e:
logger.error(e.body.decode())
return None
return envelope
at the moment I'm getting this error:
{"errorCode":"INVALID_REQUEST_BODY","message":"The request body is missing or improperly formatted. Could not cast or convert from System.String to API_REST.Models.v2_1.propertyMetadata."}
I don't understand what I could be doing wrong. Is my envelope definition not correct or is there something else I am missing. I can't seem to find official documentation on how to do this. All I have found is [https://developers.docusign.com/docs/esign-rest-api/how-to/send-binary/][1] which does not use the docusign SDK.
Any help would be welcome. Thanks!
email_subject needs to be added to envelope_definition and has some value. That's the subject of the email sent out by DocuSign.
document_id="2" instead of document_id=2
anchor_x_offset_metadata should not be used here and is probably the reason for your error.
I am trying to write a lambda that creates a tag of key 'MyID' and value of 'null'. The tag should be attached to each instance if the tag does not exist.
import boto3
client = boto3.client('ec2')
def handler(event,context):
response = client.describe_instances()
for reservation in response['Reservations']:
for instance in reservation['Instances']:
instance.create_tags(Tags={'TagName': 'TagValue'})
Here is some code that should do it:
import boto3
client = boto3.client('ec2', region_name='ap-southeast-2')
def handler(event, context):
# Get a list of instances
response = client.describe_instances()
# For each instance
for reservation in response['Reservations']:
for instance in reservation['Instances']:
# Extract existing tags
tags = [tag['Key'] for tag in instance['Tags']]
if 'MyID' not in tags:
# Add a tag
tag_response = client.create_tags(
Resources=[instance['InstanceId']],
Tags=[{'Key': 'MyID', 'Value': ''}]
)
I have created a Cloud Compute Engine instance on Debian, and have successfully created a PUSH subscription to a topic with
from google.cloud import pubsub_v1
project_id = "censored"
topic_name = "censored"
subscription_name = "censored"
endpoint = "https://censored.appspot.com/pubsub/push?token=censored"
def create_push_subscription(project_id,
topic_name,
subscription_name,
endpoint):
"""Create a new push subscription on the given topic."""
# [START pubsub_create_push_subscription]
subscriber = pubsub_v1.SubscriberClient()
topic_path = subscriber.topic_path(project_id, topic_name)
subscription_path = subscriber.subscription_path(
project_id, subscription_name)
push_config = pubsub_v1.types.PushConfig(
push_endpoint=endpoint)
subscription = subscriber.create_subscription(
subscription_path, topic_path, push_config)
print('Push subscription created: {}'.format(subscription))
print('Endpoint for subscription is: {}'.format(endpoint))
# [END pubsub_create_push_subscription]
create_push_subscription(project_id, topic_name, subscription_name, endpoint)
but I'm not sure how exactly incoming messages arrive. I have found this sample code to parse messages, but I'm not sure how to get it to monitor in the background and 'activate' whenever incoming messages arrive.
import argparse
import base64
import json
import sys
import time
from google.cloud import pubsub_v1
def summarize(message):
# [START parse_message]
data = message.data.decode('utf-8')
attributes = message.attributes
name = attributes['name']
time_created = attributes['timeCreated']
bucket_id = attributes['bucketId']
object_id = attributes['objectId']
generation = attributes['objectGeneration']
description = (
'\tName: {name}\n'
'\tTime Created: {time_created}\n'
'\tBucket ID: {bucket_id}\n'
'\tObject ID: {object_id}\n'
'\tGeneration: {generation}\n'
).format(
name=name,
time_created=time_created,
bucket_id=bucket_id,
object_id=object_id,
generation=generation
)
if 'overwroteGeneration' in attributes:
description += '\tOverwrote generation: %s\n' % (
attributes['overwroteGeneration'])
if 'overwrittenByGeneration' in attributes:
description += '\tOverwritten by generation: %s\n' % (
attributes['overwrittenByGeneration'])
payload_format = attributes['payloadFormat']
if payload_format == 'JSON_API_V1':
object_metadata = json.loads(data)
name = object_metadata['name']
time_created = object_metadata['timeCreated']
size = object_metadata['size']
content_type = object_metadata['contentType']
metageneration = object_metadata['metageneration']
description += (
'\tName: {name}\n'
'\tTime Created: {time_created}\n'
'\tContent type: {content_type}\n'
'\tSize: {object_size}\n'
'\tMetageneration: {metageneration}\n'
).format(
name=name,
time_created=time_created,
content_type=content_type,
object_size=size,
metageneration=metageneration
)
return description
print('Note for developer: If BucketId and ObjectId listed, utf encoding.')
print('If not, JSON_V1 encoding. Adjust accordingly.')
# [END parse_message]
while(True):
print("signpost 1")
summarize(message)
print("signpost 2")
time.sleep(10)
print("signpost 3")
For example, this code will return
NameError: name 'message' is not defined
which is expected...
Could someone please help me set it up properly?
I know it's different in PULL because then the message will be defined during the pull, but I'd like to keep it as PUSH, if possible.
You need to create a long-running process which is either able to continuously poll for new messages (pull subscription) or have a reachable endpoint to receive new messages (push subscription).
See the example here: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/pubsub/cloud-client/subscriber.py, as well as the differences between push and pull here: https://cloud.google.com/pubsub/docs/subscriber
I have a Django views to create a sort of AWS pack (contains account and new vpc creation), I am trying to invoke a lambda function in between that will delete the default vpc in the newly created account. Here is my snippet :
def createlab(request):
if request.method == 'POST':
lab_name = request.POST.get('labname')
cidr = request.POST.get('cidr')
bill = request.POST.get('budget')
email = request.POST.get('email')
#CREATE ACCOUNT
org = boto3.client('organizations')
acc = org.create_account(
Email=email,
AccountName=lab_name,
IamUserAccessToBilling='ALLOW'
)
time.sleep(35)
cid = acc['CreateAccountStatus']['Id']
#GET ACCOUNT DETAILS
status = org.describe_create_account_status(
CreateAccountRequestId=cid
)
print(status)
time.sleep(17)
while True:
status = org.describe_create_account_status(CreateAccountRequestId=cid)
try:
accid = status['CreateAccountStatus']['AccountId']
break
except KeyError:
time.sleep(40)
accid = status['CreateAccountStatus']['State']
#CREATE VPC
session =
boto3.Session
(aws_access_key_id=acc_key,
aws_secret_access_key=sec_key,aws_session_token=token)
ec2 = session.resource('ec2',region_name=region_ec2_sub)
vpc = ec2.create_vpc(CidrBlock=cidr)
id = vpc.id
#DELETE DEFAULT VPC
client = boto3.client('lambda',region_name='us-west-2')
deletevpc=
client.invoke(FunctionName='default_vpc',
InvocationType='RequestResponse')
print (deletevpc)
I have included a portion of my views function. I have added the #DELETE DEFAULT VPC snippet in the end. The lambda function is not getting executed. What am I doing wrong here ?
I'm trying to do a simple save string to datastore, redirect on that entity's key, then fetch it in the next handler. When I make the call in PDFHandler to fetch the string (a.name()) "w" is returned everytime, no matter what I enter.
class Pdf(db.Model):
name = db.StringProperty(required=True)
class InputHandler(Handler):
def get(self):
self.render('cert_form.html')
def post(self):
name = self.request.get('name')
if name:
a = Pdf(name=name)
a.put()
self.redirect('/key=%s' % a.key())
else:
error = "Please enter your full name."
self.render('cert_form.html')
class PDFHandler(Handler):
def get(self, id):
a = db.Key.from_path('Pdf', id)
self.response.write(a.name())
application = webapp2.WSGIApplication([
(r'/', InputHandler),
(r'/key=(.)+', PDFHandler),
], debug=True)
In your PDFHandler when you do
a = db.Key.from_path('Pdf', id)
What you are getting is the Key object not the entity yet.
To get the Pdf entity you can do the below
pdf = db.get(a)
Then you can access fields on pdf like pdf.name etc.