Building AMIs with Packer
In this example we'll run a job that creates an Amazon Machine Images (AMIs) with HashiCorp's Packer. Next we output the AMI ID from the build as a resource an consume it as an input to the job responsible for launching instances.
Resources
code-repo
- git repo containing thepacker.json
fileworker-ami
- a text file repo containing the resulting AMI ID of the AMI built with packer
resources:- name: code-repotype: gitsource:branch: mainprivate_key: ((repo_key))uri: git@gitlab.com:oozie/code-repo.git- name: worker-amitype: s3source:access_key_id: ((aws_access))secret_access_key: ((aws_secret))region_name: ((state_bucket_region))bucket: ((state_bucket))versioned_file: concourse/worker-ami.txtjobs:- name: create-worker-templateplan:- get: code-repo- task: packer-buildconfig:platform: linuximage_resource:type: docker-imagesource:repository: hashicorp/packertag: full-1.7.8inputs:- name: code-repooutputs:- name: worker-amiparams:NAME_PREFIX: ((webvm_prefix))VPC_ID: ((vpc_id))SUBNET_ID: ((subnet_id))AWS_ACCESS_KEY_ID: ((aws_access))AWS_SECRET_ACCESS_KEY: ((aws_secret))AWS_DEFAULT_REGION: ((aws_region))run:dir: code-repopath: /bin/shargs:- -c- |set -o pipefailpacker build myvmtemplate/packer.json -machine-readable | tee /tmp/packer.logecho $(grep ,artifact,0,id "/tmp/packer.log" | cut -d: -f 2) > ../worker-ami/worker-ami.txt- put: worker-amiparams:file: worker-ami/worker-ami.txt- name: spawn-workerplan:- get: code-repo- get: worker-amipassed: [ create-worker-template ]- task: ec2.create-instancesconfig:platform: linuximage_resource:type: docker-imagesource:repository: oozie/py3inputs:- name: code-repo- name: worker-amiparams:NAME_PREFIX: ((webvm_prefix))SUBNET_ID: ((subnet_id))AWS_ACCESS_KEY_ID: ((aws_access))AWS_SECRET_ACCESS_KEY: ((aws_secret))AWS_DEFAULT_REGION: ((aws_region))run:path: python3args:- -c- |import osimport boto3import timefrom pprint import pprintwith open('worker-ami/worker-ami.txt') as ami_file:ami_id = ami_file.read().strip()subnet_id = os.environ['SUBNET_ID']name_prefix = os.environ['NAME_PREFIX']ec2 = boto3.resource("ec2")secondsnow = str(int(time.time()))resp = ec2.create_instances(ImageId=ami_id, InstanceType="t2.medium",SubnetId=subnet_id,MinCount=1, MaxCount=1, TagSpecifications=[{'ResourceType': 'instance','Tags': [{'Key': 'Name','Value': f'myvm-{name_prefix}/{secondsnow}'},]},],BlockDeviceMappings=[{"DeviceName": "/dev/sda1","Ebs" : { "VolumeSize" : 80}}],)pprint(resp)