SlideShare a Scribd company logo
1 of 46
Controlling the cloud
   with Python
          Pycon.it
       9 maggio 2009
Me...




        Luca Mearelli
              http://luca.im
                    @lmea
kiaraservice.com
Cloud?



         *-as-a-service
         elastic & fluid
         scalable
         programmable
                          @lmea #pycontre #aws
Amazon Web Services




      EC2             SQS
      S3              Elastic MapReduce
      CloudFront      MechanicalTurk
      SimpleDB        ...




                                  @lmea #pycontre #aws
Boto

   http://code.google.com/p/boto



   python setup.py install
   export AWS_ACCESS_KEY_ID=<your key>
   export AWS_SECRET_ACCESS_KEY=<your secret>
   # ~/.boto
   # /etc/boto.cfg




                                            @lmea #pycontre #aws
S3 - Simple Storage Service


        storage service
        scalable
        replicated & distributed
        web aware (HTTP / bittorrent)
        flexible security
        eventually consistent

                                   @lmea #pycontre #aws
S3 - Connecting




   import boto
   conn = boto.connect_s3()
   conn = S3Connection()

   conn.is_secure
   conn = boto.connect_s3(is_secure=False)




                                             @lmea #pycontre #aws
S3 - Buckets




   bucket = conn.create_bucket('pycon3')
   rs = conn.get_all_buckets()
   for bucket in rs :
       print bucket.name

   bucket.delete()
   conn.delete_bucket('pycon3')




                                           @lmea #pycontre #aws
S3 - Keys & Objects




   from boto.s3 import Key
   key = Key(bucket)
   key = bucket.new_key('aaaa')

   key.name = 'aaaa'
   key.exists()




                                  @lmea #pycontre #aws
S3 - Keys & Objects




   key.set_contents_from_string(
           'My Test',
           headers={'Content-Type':'text/plain'})

   key.set_contents_from_filename('test.txt')




                                            @lmea #pycontre #aws
S3 - Keys & Objects




   rs = bucket.get_all_keys()
   rs = bucket.get_all_keys(prefix='test/level1/',
                            delimiter='/',
                            maxkeys=5)
   key = bucket.get_key('demo/foo')




                                            @lmea #pycontre #aws
S3 - Keys & Objects




   key = bucket.get_key('foo')

   fp = open('foo.txt', 'wb')
   key.get_contents_to_file(fp)

   s = key.get_contents_as_string()




                                      @lmea #pycontre #aws
S3 - Keys & Objects




   key.set_metadata('format', 'avi')
   key.get_metadata('format')




                                       @lmea #pycontre #aws
S3 - Permissions




   bucket.make_public(recursive=True)
   key.make_public()
   key.generate_url(10)
   key.set_acl('public-read-write')
   CannedACLStrings = ['private',
                        'public-read',
                        'public-read-write',
                        'authenticated-read']




                                                @lmea #pycontre #aws
S3 - Logging




   lb = conn.create_bucket('pycon3.logging')
   pb = conn.create_bucket('pycon3.public')
   lb.set_as_logging_target()
   pb.enable_logging(lb)




                                               @lmea #pycontre #aws
EC2 - Elastic Compute Cloud



        Computing on demand
        Any application on any OS
        Persistent/ephemeral storage
        Server customization
        Flexible security


                                    @lmea #pycontre #aws
EC2 - Connecting




   conn = boto.connect_ec2()
   conn = EC2Connection()

   regions = boto.regions()
   conn = regions[0].connect()




                                 @lmea #pycontre #aws
EC2 - Images




   rs = conn.get_all_images(owners=['012345678901'])

   image = conn.get_image(image_id='ami-5647a33f')




                                            @lmea #pycontre #aws
EC2 - Keypairs




   key_pair = conn.create_key_pair('my_key')
   key_pair.save('/Users/luca/.ssh')




                                               @lmea #pycontre #aws
EC2 - Instances




   res = conn.run_instances('ami-5647a33f',
                            instance_type='m1.small',
                            key_name='my_key',
                            min_count=1, max_count=1,
                            security_groups=['web'],
                            user_data=None)

   inst = res.instances[0]




                                            @lmea #pycontre #aws
EC2 - Instance



   while not instance.update() == 'running':
       print instance.state
       time.sleep(5)

   print   inst.id
   print   inst.public_dns_name
   print   inst.private_dns_name
   print   inst.state
   print   inst.key_name
   print   inst.launch_time




                                               @lmea #pycontre #aws
EC2 - Instance



   inst.stop()
   res.stop_all()

   inst.reboot()

   console = inst.get_console_output()
   print console.instance_id
   print console.timestamp
   print console.output




                                         @lmea #pycontre #aws
EC2 - Firewall




   group = conn.create_security_group(
                  group_name='web',
                  group_desc='Web Servers')

   rs = conn.get_all_security_groups()




                                              @lmea #pycontre #aws
EC2 - Firewall




   conn.authorize_security_group(
       'web',
       ip_protocol='tcp',
       from_port='80',
       to_port='80',
       cidr_ip='0.0.0.0/0')

   group.revoke('tcp', 80, 80, '0.0.0.0/0')




                                              @lmea #pycontre #aws
EC2 - Elastic block storage



   ebs = conn.create_volume(size,
                            zone,
                            snapshot=None)

   conn.attach_volume(volume_id=ebs.volume_id,
                      instance_id=inst.id,
                      '/sdb')

   conn.create_snapshot(volume_id)




                                             @lmea #pycontre #aws
SQS - Simple Queue Service




        Distributed queue
        Web scale
        Redundant infrastructure



                                   @lmea #pycontre #aws
SQS - Connecting




   conn = boto.connect_sqs()
   conn = SQSConnection()




                               @lmea #pycontre #aws
SQS - Queue




   queue = conn.create_queue('myqueue')
   queue.url
   #'https://queue.amazonaws.com/591131556747/myqueue'
   queue.get_timeout()
   queue.set_timeout(120)
   rs = conn.get_all_queues()
   queue = conn.get_queue('myqueue')




                                            @lmea #pycontre #aws
SQS - Messages




   from boto.sqs import Message

   msg = Message()
   msg.set_body('A test message')
   msg.attributes['timestamp'] = 1202131

   queue.write(msg)




                                           @lmea #pycontre #aws
SQS - Messages




   Message()
   MHMessage()
   RawMessage()
   JSONMessage()

   queue.set_message_class(MHMessage)




                                        @lmea #pycontre #aws
SQS - Messages




   queue.count()

   rs = queue.get_messages(num_messages=1,
                           visibility_timeout=None)

   msg = queue.read(visibility_timeout=None)

   msg.get_body()




                                               @lmea #pycontre #aws
SQS - Messages




   msg.delete()

   queue.clear()




                   @lmea #pycontre #aws
SQS - Dumping & loading




   queue.save_to_file(fp, sep='n')
   queue.load_from_file(fp)

   queue.save_to_s3(bucket, prefix=None)
   queue.load_from_s3(bucket, prefix=None)




                                             @lmea #pycontre #aws
SDB - Simple DB




        Structured data storage
        Schema-free
        Queryable



                                  @lmea #pycontre #aws
SDB - Connecting




   conn = boto.connect_sdb()
   conn = SDBConnection()




                               @lmea #pycontre #aws
SDB - Domains




   dom = conn.create_domain('pycon3')
   dom = conn.lookup('pycon3')

   rs   = conn.get_all_domains()




                                        @lmea #pycontre #aws
SDB - Domains




   md = conn.get_metadata()
   md.item_count




                              @lmea #pycontre #aws
SDB - Items




   item = dom.new_item('item1')
   item['k1'] = 'value'
   item['k2'] = 10
   item['k3'] = ['a','b','c']
   item.add_value('k3', 'd')
   item.save()




                                  @lmea #pycontre #aws
SDB - Read & query



   dom.get_item('item1')

   rs = dom.query(quot;['k1' = 'value']quot;)

   rs = dom.select(
          quot;select * from pycon3 where k1 = 'value'quot;)

   for item in rs :
        print item.name




                                            @lmea #pycontre #aws
SDB - Query examples

   quot;['city' = 'Seattle' or 'city' = 'Portland']quot;

   quot;['author' starts-with 'Robert']quot;

   quot;['author' does-not-start-with'Robert']quot;

   quot;['first name' = 'John'] intersection ['last name'
   = 'Smith']quot;

   quot;['tag' starts-with 'Amazon'] union ['description'
   = 'SimpleDB']quot;

   quot;not ['country' = 'USA' or 'country' = 'UK']quot;



                                              @lmea #pycontre #aws
SDB - Select examples

   quot;select * from mydomain where city = 'Seattle' or
   city = 'Portland'quot;

   quot;select * from mydomain where author like 'Rob%'quot;

   quot;select * from mydomain where year is not nullquot;

   quot;select * from mydomain where every(keyword) in
   ('Book', 'Paperback') quot;

   quot;select itemName() from mydomainquot;

   quot;select count(*) from mydomainquot;



                                            @lmea #pycontre #aws
SDB - Dumping to xml




   d = dom.to_xml()




                       @lmea #pycontre #aws
???
      @lmea #pycontre #aws
Grazie!
  Luca :-)




             @lmea #pycontre #aws

More Related Content

What's hot

Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worlds
Ignacio Martín
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
King Foo
 

What's hot (20)

New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)New Symfony Tips & Tricks (SymfonyCon Paris 2015)
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
 
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task Queue
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worlds
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
 
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
The Coolest Symfony Components you’ve never heard of - DrupalCon 2017
 
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
 
Building Cloud Castles
Building Cloud CastlesBuilding Cloud Castles
Building Cloud Castles
 
Symfony2 revealed
Symfony2 revealedSymfony2 revealed
Symfony2 revealed
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
With a Mighty Hammer
With a Mighty HammerWith a Mighty Hammer
With a Mighty Hammer
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
 
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and moreSymfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
 
The road to Ember.js 2.0
The road to Ember.js 2.0The road to Ember.js 2.0
The road to Ember.js 2.0
 
Django Celery
Django Celery Django Celery
Django Celery
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 

Viewers also liked (6)

Open Web
Open WebOpen Web
Open Web
 
Pasttense
PasttensePasttense
Pasttense
 
The anatomy of an infographic
The anatomy of an infographicThe anatomy of an infographic
The anatomy of an infographic
 
And Now You Have Two Problems
And Now You Have Two ProblemsAnd Now You Have Two Problems
And Now You Have Two Problems
 
Capistrano2
Capistrano2Capistrano2
Capistrano2
 
Carte De Vizita
Carte De VizitaCarte De Vizita
Carte De Vizita
 

Similar to Controlling The Cloud With Python

fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
Wesley Beary
 
Kåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your servicesKåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your services
Nordic Infrastructure Conference
 

Similar to Controlling The Cloud With Python (20)

Mastering the AWS SDK for PHP (TLS306) | AWS re:Invent 2013
Mastering the AWS SDK for PHP (TLS306) | AWS re:Invent 2013Mastering the AWS SDK for PHP (TLS306) | AWS re:Invent 2013
Mastering the AWS SDK for PHP (TLS306) | AWS re:Invent 2013
 
Alex Casalboni - Configuration management and service discovery - Codemotion ...
Alex Casalboni - Configuration management and service discovery - Codemotion ...Alex Casalboni - Configuration management and service discovery - Codemotion ...
Alex Casalboni - Configuration management and service discovery - Codemotion ...
 
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
 
fog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloudfog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloud
 
Taking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) FamilyTaking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) Family
 
Microarmy - by J2 Labs
Microarmy - by J2 LabsMicroarmy - by J2 Labs
Microarmy - by J2 Labs
 
Amazon Web Services for PHP Developers
Amazon Web Services for PHP DevelopersAmazon Web Services for PHP Developers
Amazon Web Services for PHP Developers
 
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine YardHow I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
How I Learned to Stop Worrying and Love the Cloud - Wesley Beary, Engine Yard
 
Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)Prompt engineering for iOS developers (How LLMs and GenAI work)
Prompt engineering for iOS developers (How LLMs and GenAI work)
 
AzureMLDeployment.ppt
AzureMLDeployment.pptAzureMLDeployment.ppt
AzureMLDeployment.ppt
 
Scaling Mapufacture on Amazon Web Services
Scaling Mapufacture on Amazon Web ServicesScaling Mapufacture on Amazon Web Services
Scaling Mapufacture on Amazon Web Services
 
Kåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your servicesKåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your services
 
Asynchronous Processing with Ruby on Rails (RailsConf 2008)
Asynchronous Processing with Ruby on Rails (RailsConf 2008)Asynchronous Processing with Ruby on Rails (RailsConf 2008)
Asynchronous Processing with Ruby on Rails (RailsConf 2008)
 
Cloud Computing in PHP With the Amazon Web Services
Cloud Computing in PHP With the Amazon Web ServicesCloud Computing in PHP With the Amazon Web Services
Cloud Computing in PHP With the Amazon Web Services
 
R Jobs on the Cloud
R Jobs on the CloudR Jobs on the Cloud
R Jobs on the Cloud
 
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...
DevOps Fest 2019. Alex Casalboni. Configuration management and service discov...
 
Deployment and Management on AWS:
 A Deep Dive on Options and Tools
Deployment and Management on AWS:
 A Deep Dive on Options and ToolsDeployment and Management on AWS:
 A Deep Dive on Options and Tools
Deployment and Management on AWS:
 A Deep Dive on Options and Tools
 
My First Big Data Application
My First Big Data ApplicationMy First Big Data Application
My First Big Data Application
 
Kube-AWS
Kube-AWSKube-AWS
Kube-AWS
 
(DEV301) Automating AWS with the AWS CLI
(DEV301) Automating AWS with the AWS CLI(DEV301) Automating AWS with the AWS CLI
(DEV301) Automating AWS with the AWS CLI
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 

Controlling The Cloud With Python

  • 1. Controlling the cloud with Python Pycon.it 9 maggio 2009
  • 2. Me... Luca Mearelli http://luca.im @lmea
  • 4.
  • 5. Cloud? *-as-a-service elastic & fluid scalable programmable @lmea #pycontre #aws
  • 6. Amazon Web Services EC2 SQS S3 Elastic MapReduce CloudFront MechanicalTurk SimpleDB ... @lmea #pycontre #aws
  • 7. Boto http://code.google.com/p/boto python setup.py install export AWS_ACCESS_KEY_ID=<your key> export AWS_SECRET_ACCESS_KEY=<your secret> # ~/.boto # /etc/boto.cfg @lmea #pycontre #aws
  • 8. S3 - Simple Storage Service storage service scalable replicated & distributed web aware (HTTP / bittorrent) flexible security eventually consistent @lmea #pycontre #aws
  • 9. S3 - Connecting import boto conn = boto.connect_s3() conn = S3Connection() conn.is_secure conn = boto.connect_s3(is_secure=False) @lmea #pycontre #aws
  • 10. S3 - Buckets bucket = conn.create_bucket('pycon3') rs = conn.get_all_buckets() for bucket in rs : print bucket.name bucket.delete() conn.delete_bucket('pycon3') @lmea #pycontre #aws
  • 11. S3 - Keys & Objects from boto.s3 import Key key = Key(bucket) key = bucket.new_key('aaaa') key.name = 'aaaa' key.exists() @lmea #pycontre #aws
  • 12. S3 - Keys & Objects key.set_contents_from_string( 'My Test', headers={'Content-Type':'text/plain'}) key.set_contents_from_filename('test.txt') @lmea #pycontre #aws
  • 13. S3 - Keys & Objects rs = bucket.get_all_keys() rs = bucket.get_all_keys(prefix='test/level1/', delimiter='/', maxkeys=5) key = bucket.get_key('demo/foo') @lmea #pycontre #aws
  • 14. S3 - Keys & Objects key = bucket.get_key('foo') fp = open('foo.txt', 'wb') key.get_contents_to_file(fp) s = key.get_contents_as_string() @lmea #pycontre #aws
  • 15. S3 - Keys & Objects key.set_metadata('format', 'avi') key.get_metadata('format') @lmea #pycontre #aws
  • 16. S3 - Permissions bucket.make_public(recursive=True) key.make_public() key.generate_url(10) key.set_acl('public-read-write') CannedACLStrings = ['private', 'public-read', 'public-read-write', 'authenticated-read'] @lmea #pycontre #aws
  • 17. S3 - Logging lb = conn.create_bucket('pycon3.logging') pb = conn.create_bucket('pycon3.public') lb.set_as_logging_target() pb.enable_logging(lb) @lmea #pycontre #aws
  • 18. EC2 - Elastic Compute Cloud Computing on demand Any application on any OS Persistent/ephemeral storage Server customization Flexible security @lmea #pycontre #aws
  • 19. EC2 - Connecting conn = boto.connect_ec2() conn = EC2Connection() regions = boto.regions() conn = regions[0].connect() @lmea #pycontre #aws
  • 20. EC2 - Images rs = conn.get_all_images(owners=['012345678901']) image = conn.get_image(image_id='ami-5647a33f') @lmea #pycontre #aws
  • 21. EC2 - Keypairs key_pair = conn.create_key_pair('my_key') key_pair.save('/Users/luca/.ssh') @lmea #pycontre #aws
  • 22. EC2 - Instances res = conn.run_instances('ami-5647a33f', instance_type='m1.small', key_name='my_key', min_count=1, max_count=1, security_groups=['web'], user_data=None) inst = res.instances[0] @lmea #pycontre #aws
  • 23. EC2 - Instance while not instance.update() == 'running': print instance.state time.sleep(5) print inst.id print inst.public_dns_name print inst.private_dns_name print inst.state print inst.key_name print inst.launch_time @lmea #pycontre #aws
  • 24. EC2 - Instance inst.stop() res.stop_all() inst.reboot() console = inst.get_console_output() print console.instance_id print console.timestamp print console.output @lmea #pycontre #aws
  • 25. EC2 - Firewall group = conn.create_security_group( group_name='web', group_desc='Web Servers') rs = conn.get_all_security_groups() @lmea #pycontre #aws
  • 26. EC2 - Firewall conn.authorize_security_group( 'web', ip_protocol='tcp', from_port='80', to_port='80', cidr_ip='0.0.0.0/0') group.revoke('tcp', 80, 80, '0.0.0.0/0') @lmea #pycontre #aws
  • 27. EC2 - Elastic block storage ebs = conn.create_volume(size, zone, snapshot=None) conn.attach_volume(volume_id=ebs.volume_id, instance_id=inst.id, '/sdb') conn.create_snapshot(volume_id) @lmea #pycontre #aws
  • 28. SQS - Simple Queue Service Distributed queue Web scale Redundant infrastructure @lmea #pycontre #aws
  • 29. SQS - Connecting conn = boto.connect_sqs() conn = SQSConnection() @lmea #pycontre #aws
  • 30. SQS - Queue queue = conn.create_queue('myqueue') queue.url #'https://queue.amazonaws.com/591131556747/myqueue' queue.get_timeout() queue.set_timeout(120) rs = conn.get_all_queues() queue = conn.get_queue('myqueue') @lmea #pycontre #aws
  • 31. SQS - Messages from boto.sqs import Message msg = Message() msg.set_body('A test message') msg.attributes['timestamp'] = 1202131 queue.write(msg) @lmea #pycontre #aws
  • 32. SQS - Messages Message() MHMessage() RawMessage() JSONMessage() queue.set_message_class(MHMessage) @lmea #pycontre #aws
  • 33. SQS - Messages queue.count() rs = queue.get_messages(num_messages=1, visibility_timeout=None) msg = queue.read(visibility_timeout=None) msg.get_body() @lmea #pycontre #aws
  • 34. SQS - Messages msg.delete() queue.clear() @lmea #pycontre #aws
  • 35. SQS - Dumping & loading queue.save_to_file(fp, sep='n') queue.load_from_file(fp) queue.save_to_s3(bucket, prefix=None) queue.load_from_s3(bucket, prefix=None) @lmea #pycontre #aws
  • 36. SDB - Simple DB Structured data storage Schema-free Queryable @lmea #pycontre #aws
  • 37. SDB - Connecting conn = boto.connect_sdb() conn = SDBConnection() @lmea #pycontre #aws
  • 38. SDB - Domains dom = conn.create_domain('pycon3') dom = conn.lookup('pycon3') rs = conn.get_all_domains() @lmea #pycontre #aws
  • 39. SDB - Domains md = conn.get_metadata() md.item_count @lmea #pycontre #aws
  • 40. SDB - Items item = dom.new_item('item1') item['k1'] = 'value' item['k2'] = 10 item['k3'] = ['a','b','c'] item.add_value('k3', 'd') item.save() @lmea #pycontre #aws
  • 41. SDB - Read & query dom.get_item('item1') rs = dom.query(quot;['k1' = 'value']quot;) rs = dom.select( quot;select * from pycon3 where k1 = 'value'quot;) for item in rs : print item.name @lmea #pycontre #aws
  • 42. SDB - Query examples quot;['city' = 'Seattle' or 'city' = 'Portland']quot; quot;['author' starts-with 'Robert']quot; quot;['author' does-not-start-with'Robert']quot; quot;['first name' = 'John'] intersection ['last name' = 'Smith']quot; quot;['tag' starts-with 'Amazon'] union ['description' = 'SimpleDB']quot; quot;not ['country' = 'USA' or 'country' = 'UK']quot; @lmea #pycontre #aws
  • 43. SDB - Select examples quot;select * from mydomain where city = 'Seattle' or city = 'Portland'quot; quot;select * from mydomain where author like 'Rob%'quot; quot;select * from mydomain where year is not nullquot; quot;select * from mydomain where every(keyword) in ('Book', 'Paperback') quot; quot;select itemName() from mydomainquot; quot;select count(*) from mydomainquot; @lmea #pycontre #aws
  • 44. SDB - Dumping to xml d = dom.to_xml() @lmea #pycontre #aws
  • 45. ??? @lmea #pycontre #aws
  • 46. Grazie! Luca :-) @lmea #pycontre #aws