yoshiwaan
yoshiwaan

Reputation: 479

Chef set attribute from library code/definition

Quick context: I want to write a recipe that changes dynamically based on the AWS region that an instance is in. I want to install the CodeDeploy agent which downloads from an S3 bucket based on the region of the instance. As such I need an attribute which is set to the region

The AWS public cookbook has the code to do this but it's not set to an attribute:

def instance_availability_zone
  @@instance_availability_zone ||= query_instance_availability_zone
end
...
 def query_instance_availability_zone
  availability_zone = open('http://169.254.169.254/latest/meta-data/placement/availability-zone/', options = { proxy: false }) { |f| f.gets }
  fail 'Cannot find availability zone!' unless availability_zone
  Chef::Log.debug("Instance's availability zone is #{availability_zone}")
  availability_zone
end

It's even used in the same class in a way that would get the region in the format I want

def create_aws_interface(aws_interface)
  begin
    require 'aws-sdk'
    rescue LoadError
    Chef::Log.error("Missing gem 'aws-sdk'. Use the default aws recipe to install it first.")
  end
  region = instance_availability_zone
  region = region[0, region.length - 1]
...

So I want to have the region above set to the attribute node['was']['region'] or some such, but I lack the skill to do so. I would think I need to put this in a definition and then call it somehow?

Summary of the question: How can I set an attribute in chef via running ruby code (from a library file)?

Here's the cookbook: https://github.com/opscode-cookbooks/aws

Upvotes: 0

Views: 1045

Answers (1)

Tejay Cardon
Tejay Cardon

Reputation: 4223

You could let ohai do the work.

node[ec2][placement_availability_zone] is set by ohai. You'd just need to parse out the region from the overall AZ string.

node[ec2][placement_availability_zone].match(/.*-\d/) will do the trick, I believe.

If you are using an VPC node, you will need to add the ec2 hint for ohai. This can be most easily accomplished by passing --hint ec2 when bootstrapping the node.

Upvotes: 1

Related Questions