Reputation: 5313
I am deploying my application via code-pipeline. During that, I am calling a Lambda function to notify users on Slack. I want to add the commit name to it. Any idea how I can get that info.
Code :
import json
import http.client
import urllib.parse
from time import strftime
import boto3
import datetime
import dateutil.tz
WEBHOOK_URL = "https://hooks.slack.com/services/TOKEN"
NOTIFICATION_CHANNEL = "CHANNEL-NAME"
eastern = dateutil.tz.gettz('Europe/Berlin')
final_time = datetime.datetime.now(tz=eastern).strftime("%a, %d %b %Y %I:%M:%S %p %Z")
def lambda_handler(event, context):
send_message("Deployment for https://ourdomain.com has started at %s"%final_time,":ghost:","webhookbot")
job_id = event['CodePipeline.job']['id']
put_job_success(job_id,"Code executed")
def put_job_success(job, message):
print('Putting job success')
print(message)
code_pipeline = boto3.client('codepipeline')
code_pipeline.put_job_success_result(jobId=job)
def send_message(message, icon, username):
payload = get_payload(username, icon, message)
data = get_encoded_data_object(payload)
headers = get_headers()
response = send_post_request(data, headers)
def get_payload(username, icon, message):
payload_dict = {
'channel': NOTIFICATION_CHANNEL,
'username': username,
'icon_emoji': icon,
'text': message,
}
payload = json.dumps(payload_dict)
return payload
def get_encoded_data_object(payload):
values = {'payload': payload}
str_values = {}
for k, v in values.items():
str_values[k] = v.encode('utf-8')
data = urllib.parse.urlencode(str_values)
return data
def get_headers():
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
return headers
def send_post_request(body, headers):
https_connection = get_https_connection_with_slack()
https_connection.request('POST', WEBHOOK_URL, body, headers)
response = https_connection.getresponse()
return response
def get_https_connection_with_slack():
h = http.client.HTTPSConnection('hooks.slack.com')
return h
Upvotes: 3
Views: 765
Reputation: 461
You can write it to a file during the build phase (which I assume you will execute before) and pass the output artifacts of the build phase as input artifacts to lambda. Then within the lambda you can access its input artifact (e.g. with an s3 client) and read off the commit.
Here you can find an example of an event containing input artifacts: https://medium.com/@codershunshun/how-to-invoke-aws-lambda-in-codepipeline-d7c77457af95
Upvotes: 1