Skip to content

Commit

Permalink
add ami lookup custom resource
Browse files Browse the repository at this point in the history
  • Loading branch information
Guslington committed Sep 29, 2020
1 parent 1c972f6 commit 6318f91
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 3 deletions.
1 change: 1 addition & 0 deletions jenkins-ec2-agents.cfhighlander.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@
ComponentParam 'Subnets', type: 'CommaDelimitedList'
end

LambdaFunctions 'ami_finder_custom_resources'

end
10 changes: 8 additions & 2 deletions jenkins-ec2-agents.cfndsl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,24 @@
Tags agent_tags
}

Resource(:LinuxAmiFinder) {
Type 'Custom::LinuxAmiFinder'
Property 'ServiceToken', FnGetAtt(:AmiFinderCR, :Arn)
Property 'Name', linux_ami
}

SSM_Parameter(:LinuxAmiParameter) {
Description "AMI Id for the Jenkins linux agent"
Name FnSub("/ciinabox/${EnvironmentName}/agent/linux/ami")
Property('Tier','Standard')
Type 'String'
Value 'ami-replaceme'
Value Ref(:LinuxAmiFinder)
Property('Tags',{
Name: "#{external_parameters[:component_name]}-linux-ami",
EnvironmentName: Ref(:EnvironmentName)
})
}

SSM_Parameter(:WindowsAmiParameter) {
Description "AMI Id for the Jenkins linux agent"
Name FnSub("/ciinabox/${EnvironmentName}/agent/windows/ami")
Expand Down
30 changes: 29 additions & 1 deletion jenkins-ec2-agents.config.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
linux_ami: 'Amzn2_Linux_Jenkins_Agent-*'

iam_policies:
sts:
action:
Expand Down Expand Up @@ -27,4 +29,30 @@ iam_policies:
- ssmmessages:CreateControlChannel
- ssmmessages:CreateDataChannel
- ssmmessages:OpenControlChannel
- ssmmessages:OpenDataChannel
- ssmmessages:OpenDataChannel

ami_finder_custom_resources:
custom_policies:
ami:
action:
- ec2:DescribeImages
resource: '*'
lambda:
action:
- lambda:InvokeFunction
resource:
Fn::Sub: arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:AmiFinderCR
roles:
AmiFinderResource:
policies_inline:
- cloudwatch-logs
- ami
- lambda
functions:
AmiFinderCR:
code: ami_finder/app.py
handler: app.handler
runtime: python3.8
timeout: 600
role: AmiFinderResource
package_cmd: 'pip install -r requirements.txt -t .'
41 changes: 41 additions & 0 deletions lambdas/ami_finder/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import boto3
from crhelper import CfnResource
import logging
import json

logger = logging.getLogger(__name__)
# Initialise the helper, all inputs are optional, this example shows the defaults
helper = CfnResource(json_logging=False, log_level='DEBUG', boto_level='CRITICAL')

@helper.create
def create(event, context):
logger.info(f"Creating resource {event}")
return get_latest_ami(event['ResourceProperties']['Name'])

@helper.update
def update(event, context):
logger.info(f"Updating resource {event}")
return get_latest_ami(event['ResourceProperties']['Name'])

@helper.delete
def delete(event, context):
logger.info(f"Deleting resource {event}")

def get_latest_ami(name):
client = boto3.client('ec2')

filters = []
filters.append({'Name': 'name', 'Values': [name]})
response = client.describe_images(Filters=filters)

if not response['Images']:
return None

response['Images'].sort(key=lambda r: r['CreationDate'])
return response['Images'][-1]['ImageId']

def handler(event, context):
helper(event, context)


'Amzn2_Linux_Jenkins_Agent-*'
1 change: 1 addition & 0 deletions lambdas/ami_finder/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
crhelper

0 comments on commit 6318f91

Please sign in to comment.