Search code examples
pythonamazon-web-servicesbotoamazon-cloudfront

Amazon CloudFront distribution_id as a credential with Boto


I'm new to Python and Boto, I've managed to sort out file uploads from my server to S3. But once I've uploaded a new file I want to do an invalidation request.

I've got the code to do that:

import boto

print 'Connecting to CloudFront'
cf = boto.connect_cloudfront()
cf.create_invalidation_request(aws_distribution_id, ['/testkey'])

But I'm getting an error: NameError: name 'aws_distribution_id' is not defined

I guessed that I could add the distribution id to the ~/.boto config, like the aws_secret_access_key etc:

$ cat ~/.boto 
[Credentials]
aws_access_key_id = ACCESS-KEY-ID-GOES-HERE
aws_secret_access_key = ACCESS-KEY-SECRET-GOES-HERE
aws_distribution_id = DISTRIBUTION-ID-GOES-HERE

But that's not actually listed in the docs, so I'm not too surprised it failed: http://docs.pythonboto.org/en/latest/boto_config_tut.html

My problem is I don't want to add the distribution_id to the script as I run it on both my live and staging servers, and I have different S3 and CloudFront set ups for both.

So I need the distribution_id to change per server, which is how I've got the the AWS access keys set.

Can I add something else to the boto config or is there a python user defaults I could add it to?


Solution

  • I solved this by using the ConfigParser. I added the following to the top of my script:

    import ConfigParser
    
    # read conf
    config = ConfigParser.ConfigParser()
    config.read('~/my-app.cnf')
    distribution_id = config.get('aws_cloudfront', 'distribution_id')
    

    And inside the conf file at ~/.my-app.cnf

    [aws_cloudfront]
    distribution_id = DISTRIBUTION_ID
    

    So on my live server I just need to drop the cnf file into the user's home dir and change the distribution_id