66
Formation Introduction à BOTO

Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Embed Size (px)

Citation preview

Page 1: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Formation

Introduction à BOTO

Page 2: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Introduction à Boto

Formation AWS Boto

2

Page 3: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Plan• Présentation & Installation• Concepts généraux• Zoom sur EC2 et S3• Alternatives

Formation AWS Boto

3

Page 4: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Présentation & Installation

Formation AWS Boto

4

Page 5: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Historique• Créé par Mitch Garnaat en 2006• Bibliothèque Python 2.6+• Support Python 3.x en cours (cf. botocore)• Supporte l'ensemble des services AWS• Supporte également :

• Eucalyptus• Google Storage• OpenStack• OpenNebula

Formation AWS Boto

5

Page 6: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Pour l'anecdote

Formation AWS Boto

6

haikel
Boto vermelho ou “dauphin rose” est une espèce de dauphin qui vit dans le fleuve Amazone.D'où le nom de la bibliothèque ;)
Page 7: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Installer Boto• Utiliser le système de paquetages de votre distribution

apt-get install python-boto

yum install python-boto

• Via githubgit clone https://github.com/boto/boto && cd boto && python setup.py install

• Le Python Cheese Shop (aka PyPI) virtualenv test && cd test && source bin/activate && pip install boto

Formation AWS Boto

7

Page 8: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Concepts Généraux

Formation AWS Boto

8

Page 9: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Principes de base• Module principal : « boto »

• Configuration• Logs• Méthodes de convenance connect_<service> pour obtenir

un objet Connection à un service AWS spécifique• Un module boto.<service> par service AWS (ex : boto.ec2, boto.sqs)

• Chaque module fournit une méthode connect_to_region()

Formation AWS Boto

9

Page 10: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Connections• On récupére un objet connection à un service pour une région donnée• C'est à travers cet objet qu'on manipulera notre service• Paramètres communs aux méthodes connect_<service>()

• aws_access_key• aws_secret_access_key• is_secure: force l'utilisation de HTTPS• region: objet boto.<service>.regioninfo.RegionInfo

initialisé avec le nom de la région• debug

Formation AWS Boto

10

Page 11: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Documentation en ligne

Formation AWS Boto

11

http://boto.readthedocs.org

Page 12: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

EC2

Formation AWS Boto

12

Page 13: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Instance (1)• Un objet boto.ec2.instance.Instance représente une instance EC2• Quelques attributs utiles

• id : identifiant de l'instance• groups : groupe de sécurité (politique pare-feu)• State : état de l'instance• instance_type : type de l'instance• image_id : identifiant de l'AMI• public_dns_name : nom DNS publique de l'instance• private_dns_name : nom DNS privé de l'instance

Formation AWS Boto

13

Page 14: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Instance (2)• Opérations courantes

• start() démarrer l'instance• stop() mettre en pause l'instance

(instance EBS uniquement)• terminate() arrêter définitivement l'instance• reboot() redémarrer une instance en pause• add_tag()/remove_tag() ajouter/enlever un tag à

l'instance• update() mettre à jour les informations de

l'instance

Formation AWS Boto

14

Page 15: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Réservation• boto.ec2.instance.Reservation représente une

réservation EC2• Conteneur d'instances (attribut : instances)• Une méthode utile : stop_all()

Formation AWS Boto

15

Page 16: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Connexion à EC2import boto

import boto.ec2

conn = boto.connect_ec2()

# alternatives

# conn = boto.ec2.EC2Connection()

Formation AWS Boto

16

Page 17: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Lister les AMI disponibles# Lister les AMI SysFera

amis = conn.get_all_images(owners=

[443252058477])

# récupérer une AMI particulière

ami = conn.get_image(image_id='ami-2ea50247')

Formation AWS Boto

17

haikel
La méthode get_all_images() est bogué, il faut impérativement passer les owner idPour récupérer son ownerId, pas d'APIconn.get_all_security_groups()[0].owner_idu'443252058477'=> SysFera's owner id
Page 18: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Démarrer une instance EC2Reservation = conn.run_instances('ami-xxx',

key_name= key_name, security_groups=['ssh-group'], instance_type='m1.small', user_data=user_data)

instance = reservation.instances[0]

Formation AWSBoto

18

Page 19: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Connaître l'état d'une instance EC2# mettre à jour les informations

instance.update()

# afficher les informations

print instance.state

print instance.public_dns_name

print instance.launch_time

Formation AWS Boto

19

Page 20: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Terminer une instance EC2# récupérer la réservation

resa = conn.get_all_instances(filters={'tag:Name' : 'prod1'})[0]

# récupérer l'instance

instance = resa[0]

instance.terminate()

# on peut également tuer toutes les instances

# resa.terminate_all()

Formation AWS Boto

20

Page 21: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Créer un groupe de sécuritétry :

# on vérifie que le groupe n'existe pas

group = conn.get_all_security_groups('ssh-access')

except EC2ResponseError as e :

# on crée un groupe

group = conn.create_security_group('ssh-access', 'open ssh port')

Formation AWS Boto

21

Page 22: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Configurer un groupe de sécurité# ajouter une règle

group.authorize('tcp', 22, 22, '0.0.0.0/0')

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

# supprimer une règle

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

Formation AWS Boto

22

Page 23: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Allouer une EIPeip = conn.allocate_address()

conn.associate_address(instance.id, eip.public_ip)

# ou bien instance.use_ip(eip)

conn.disassociate_address(eip)

Formation AWS Boto

23

Page 24: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

EBS# créer un volume de 2Go

vol = conn.create_volume(2, 'eu-west-1a',

snapshot=None)

# attacher le volume

conn.attach_volume(volume_id=vol.id, instance_id=instance.id, '/dev/sdb')

# créer un snapshot

conn.create_snapshot(vol.id)

Formation AWS Boto

24

haikel
Le param snapshot dans la création de volume est ici uniquement à titre indicatif (None est le param par défaut) pour la création de volume à partir de snapshot)
Page 25: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

S3

Formation AWS Boto

25

Page 26: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Connexion à S3import boto

from boto.s3.connection import Location

from boto.s3.key import Key

conn = boto.connect_s3()

Formation AWS Boto

26

Page 27: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Créer un bucket# créer un bucket

bucket_EN = conn.create_bucket('thumbnails')

# créer un bucket dans la région eu-west-1

bucket_FR = conn.create_bucket('vignettes', location=Location.EU)

Formation AWS Boto

27

Page 28: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Lister les bucketrs = conn.get_all_buckets()

for bucket in rs :

print bucket.name

Formation AWS Boto

28

Page 29: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Stocker des données (1)# stocker une image à partir d'un fichier

k = Key(bucket_FR)

k.key = 'boto_vermelho.jpg'

k.set_content_from_filename('~/images/boto_vermelho.jpg')

# télécharger un objet dans un fichier

k.get_content_to_filename('foobar.jpg’)

Formation AWS Boto

29

Page 30: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Stocker des données (2)# stocker des données brutes

k.key = 'vermelho'

k.set_content_from_string('rose' ,

headers = {'Content-Type':'text/plain'})

# plus tard

k = bucket.get_key('vermelho')

content = k.get_content_as_string()

Formation AWS Boto

30

haikel
Le header content-type permet de configurer le bon type mime pour les téléchargements via HTTP
Page 31: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Lister le contenu d'un bucket# récupérer un bucket à partir de son nom

bucket = conn.lookup('toto')

keys = bucket.list()

# keys = bucket.get_all_keys()

for k in keys :

print '{0} (size : {1} ko)'.format(k.name, k.size)

# lister les clés préfixé par test/bidule

Keys = bucket.get_all_keys(prefix='test/bidule',delimiter='/')

Formation AWS Boto

31

Page 32: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Métadonnéesk.set_metadata('lieu', 'amazonie')

lieu = k.get_metadata('lieu')

Formation AWS Boto

32

Page 33: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Gestion des ACL# rendre public un bucket

b.make_public(recursive=True)

# rendre public un objet à partir de sa key

k.make_public()

k.generate_url(3600) # durée de vie : 1h

k.set_acl('public-read-write')

k.set_acl('private-read-write')

Formation AWS Boto

33

Page 34: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

ELB

Formation AWS Boto

34

Page 35: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Connexion à ELBimport boto

from boto.ec2.elb import HealthCheck

conn = boto.connect_elb()

Formation AWS Boto

35

Page 36: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Définir un HealthCheck# un check toutes les 20s

# sur la ressource HTTP:8080/health

# 3 checks réussis => ressource active

# 5 checks échoués => ressource inactive

hc = HealthCheck(interval=20,

healthy_threshold=3,

unhealthy_threshold=5,

target='HTTP:8080/health')

Formation AWS Boto

36

Page 37: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Création d'un load balancerzones = ['us-east-1a', 'us-east-1b']

ports = [(80, 8080, 'http'), (443, 8443, 'https')]

lb = conn.create_load_balancer('lb1', zones, ports)

# associer notre HealthCheck à notre LB

lb.configure_health_check(hc)

# récupérer le nom DNS du LB

print lb.dns_name

Formation AWS Boto

37

Page 38: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Ajouter des instances à un LB# ajouter des instances

instances = ['i_xxxx', 'i_yyyy']

lb.register_instances(instances)

# les retirer

lb.deregister_instances(instances)

Formation AWS Boto

38

Page 39: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Manipuler les zones dans un LB# désactiver une zone

lb.disable_zone(['us-east-1a'])

# activer une zone

lb.enable_zone(['us-east-1b'])

Formation AWS Boto

39

Page 40: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Détruire un Load Balancerlb.delete()

Formation AWS Boto

40

Page 41: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

SQS

Formation AWS Boto

41

Page 42: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Connexion à SQSimport boto

from boto import Message

conn = boto.connect_sqs()

Formation AWS Boto

42

Page 43: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Création d'une fileq = conn.create_queue('tasks')

# récupérer l'url d'une queue

print q.url

https://queue.amazonaws.com/443252058477/tasks

Formation AWS Boto

43

Page 44: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Récupérer une file# lister l'ensemble des files

rs = conn.get_all_queues()

for i in rs :

print i.name

q = conn.get_queue('tasks')

Formation AWS Boto

44

Page 45: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Envoi d'un messagemsg = message() # par défaut encodage base64

msg.set_body('hello world')

msg.attributes['hostname'] = socket.gethostname()

q.write(msg)

Formation AWS Boto

45

Page 46: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Consommer un message (1)# nombre de messages dans une queue

print q.count()

# récupérer un message

msg = q.read()

# récupérer plusieurs messages

msgs = q.get_all_messages(num_messages=20)

# afficher le contenu du message

print msg.get_body()

Formation AWS Boto

46

Page 47: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Consommer un message (2)# attention récupérer un message, ne veut pas dire => consommer !

print q.count()

# valider la consommation

msg.delete() # ou q.delete_message(msg)

Formation AWS Boto

47

#

Page 48: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Sauvegarder/Restaurer une file# dans un fichier

q.save_to_filename('tasks_backup', sep='\n')

q.load_from_filename('tasks_backup')

# dans S3 (sous le schéma <queue_id>/<message_id>)

q.save_to_s3(bucket_bak, prefix=None)

q.load_from_s3()

Formation AWS Boto

48

Page 49: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Détruire notre file# vider la file

q.clear()

# destruction

Conn.delete_queue(q)

Formation AWS Boto

49

Page 50: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

SimpleDB

Formation AWS Boto

50

Page 51: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Connexion à SimpleDB

import boto

conn = boto.connect_sdb()

Formation AWS Boto

51

Page 52: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Création d'un domaine# on vérifie que le domaine n'existe pas

domain = conn.lookup('commandes')

if domain is None :

domain = conn.create_domain('commandes')

# lister les domaines

rs =conn.get_all_domains()

# autre façon de récupérer un domaine

domain = conn.get_domain('commandes')

Formation AWS Boto

52

Page 53: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Métadonnées associés à un domainemd = domain.domain_metadata()

# lister les attributs disponibles

dir(md)

# lister le nombre d'items dans le domaine

print md.item_count

Formation AWS Boto

53

Page 54: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Insérer un item# en un coup

domain.put_attributes('cmd1', {'id' : 1, 'nb' : 7})

# en plusieurs coups

item = domaine.new_item('cmd2')

item['id'] = 1

item.add_value('nb', 9)

item.save()

# en batch

domain.put_attributes({'cmd4' : {'id' : 1, 'nb' : 7}})

Formation AWS Boto

54

Page 55: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Récupérer un item (1)item = domain.get_item('cmd7')

# forcer une lecture vérouillée

item = domain.get_item('cmd7', consistent_read=True)

Formation AWS Boto

55

Page 56: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Récupérer un item (2)# possibilité d'utiliser « SQL »

rs = dom.select(select * from commandes where id="7"')

for i in rs :

print i

Formation AWS Boto

56

Page 57: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Sauvegarde XMLdoc = domain.to_xml()

Formation AWS Boto

57

Page 58: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Alternatives

Formation AWS Boto

58

Page 59: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Libcloud (1)• Bibliothèque Python• Couche d'abstraction entre les API des différents fournisseurs d'IaaS• Supporte

• Service d'instances virtuelles• Service de stockage• Service de load balancing• Service de DNS

Formation AWS Boto

59

Page 60: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Libcloud (2)• Plus de 26 fournisseurs supportés

• AWS, Rackspace, Eucalyptus, OpenStack, OpenNebula, CloudSigma, Google Storage, Vsphere, Gandi.net, etc...

Formation AWS Boto

60

https://libcloud.apache.org

Page 61: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Deltacloud (1)

Formation AWS Boto

61

Page 62: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Deltacloud (2)• Couche d'abstraction sous forme d'API REST• Développé en Ruby par Red Hat• Accessible directement par des requêtes et des bibliothèques clients (Ruby, Python, C, C++) et via Curl• Top Level Project Apache

Formation AWS Boto

62

Page 63: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Deltacloud (3)• Architecture flexible :

• Un proxy REST• 3 API en frontend : deltacloud, EC2 et CIMI• Des pilotes pour gérer différents fournisseurs

• Supporte environ 15 fournisseurs• AWS, Rackspace, OpenStack, OpenNebula, Eucalyptus, Azure

(stockage), vSphere etc.• Pilote « mock » pour tester ses applications !

Formation AWS Boto

63

Page 64: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Formation AWS Boto

64

Autres Langages• SDK officiel pour les langages PHP, Ruby, Java, .Net

https://aws.amazon.com/developertools

• En Ruby, l'excellent Fog :• Gère plusieurs fournisseurs• Supporte libvirt• Mode « mock » pour les tests

http://fog.io/

Page 65: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Formation AWS Boto

65

Bibliographie

Page 66: Formation Introduction à BOTO. Introduction à Boto Formation AWSBoto 2

Mise en pratique

Formation AWS Boto

66