• CLI

sdk
  1. Help Center
  2. CLI
  3. Developer Guide
  4. SDK
  5. Python
  6. ECS Python SDK Demo

ECS Python SDK Demo

Creating an ECS

  1. Obtain a flavor ID.

    You can use the following code to query all flavors and use a qualified flavor ID to create an ECS:

    def list_flavors(conn): 
        print("List Flavors:") 
        for flavor in conn.compute.flavors(): 
            print(flavor)
  2. Create a security group.

    For details about how to create a security group, see section How Can I Create a Security Group?.

    Optionally, you can create a security group using Python OpenStack SDK based on the following code:

    def create_security_groups(conn): 
        #create_SG 
        testSGName = "PythonSDKSG" 
        createdSG = conn.network.create_security_group( 
            name = testSGName 
            ) 
        # open a port. 
        conn.network.security_group_open_port(createdSG.id, 8080,     protocol='tcp') 
        #allow ping 
        conn.network.security_group_allow_ping(createdSG.id) 
        # More detailed rules 
        IPV4 = 'IPv4' 
        PROTO = 'tcp' 
        PORT = 22 
        DIR = 'ingress' 
        conn.network.create_security_group_rule( 
            direction=DIR,  
            ethertype=IPV4, 
            port_range_max=PORT, 
            port_range_min=PORT, 
            protocol=PROTO,  
            security_group_id=createdSG.id 
            )
  3. Create a key pair.

    For details about how to create a private key pair, see section How Can I Create a Key Pair on the Console?.

    Optionally, you can create a key pair using Python OpenStack SDK based on the following code:

    def create_keypair(conn): 
        keypair = conn.compute.find_keypair(KEYPAIR_NAME) 
        if not keypair: 
            print("Create Key Pair:") 
            keypair = conn.compute.create_keypair(name=KEYPAIR_NAME) 
            print(keypair) 
            try: 
                os.mkdir(SSH_DIR) 
            except OSError as e: 
                if e.errno != errno.EEXIST: 
                    raise e 
            with open(PRIVATE_KEYPAIR_FILE, 'w') as f: 
                f.write("%s" % keypair.private_key) 
            os.chmod(PRIVATE_KEYPAIR_FILE, 0o400) 
        return keypair
  4. Create an ECS.

    You can use the following code to create an ECS. You can use interface wait_for_serve() to continuously query the ECS status until the ECS is in the specified status or the query times out. You can modify the parameters as required. In the following example, the timeout interval is 4 minutes by default.

    def create_vm(conn): 
        server = conn.compute.create_server( 
           name='server_name', flavor_id='flavorId', image_id='imageID', key_name='keypairName',networks=[{"uuid": 'networkId'}]) 
        conn.compute.wait_for_server(server)
Table 1 Parameter description

Parameter

Description

Example Value

flavorId

Specifies the ID of the flavor.

normal2

imageId

Specifies the ID of the image.

51b2c37f-f5bd-40e0-8aa2-1899a6bbca30

keypairName

Specifies the key pair name.

mykeypair

Binding an EIP to an ECS

  1. Query the ECS port ID.
    def get_vm_port_id(conn): 
        ifs = list(conn.compute.server_interfaces(self.server)) 
        port_id = ifs[0].port_id
  2. Create the EIP.
def createEIP(conn): 
    eip = conn.network.create_ip(floating_network_id='external_network_id ',port_id='port_id') 
    count = 1 
    createFlag = False 
    while(count < 10): 
        if(conn.network.get_ip(fip.id).status == 'ACTIVE'): 
            createFlag = True 
            print 'eip created success' 
            break; 
        count = count + 1 
        sleep(1) 
    if(not createFlag): 
         print 'eip create failed'

external_network_id indicates the external network ID. For details, see section External Network.

The EIP is automatically bound to the ECS identified by the ECS port ID specified in the preceding code.

Unbinding an EIP from an ECS

You can unbind an EIP from an ECS based on the following code.

The unbinding operation takes several seconds, and the EIP can be deleted only after it is unbound. An error message may be reported if you delete an EIP during the unbinding operation.

def disassociate_eip(conn):             
    conn.compute.remove_floating_ip_from_server(server, 
eip.floating_ip_address) 
    disCount = 1 
    removeFlag = False 
    while(disCount < 10): 
        if(conn.network.get_ip(eip.id).status == 'DOWN'): 
            removeFlag = True 
            print 'eip disassociate success' 
            break; 
         count = count + 1 
         sleep(1) 
    if(not removeFlag): 
            print 'eip disassociate failed'

Deleting an ECS

The ECS deletion process takes several seconds.

def delete_server(conn): 
    conn.compute.delete_server('serverId') 
    conn.compute.wait_for_delete(cls.server)

Querying the ECS Status

Use the following code to query the ECS status:

def get_ecs(conn): 
    print conn.compute.get_server('serverID').status

(Optional) Modifying the ECS Flavor

After the flavor is modified, you can roll back the modification or make the modification take effect.

  1. Modify the flavor.
    def resize_server(conn): 
        conn.compute.resize_server(server,'resizeFlavorId') 
        conn.compute.wait_for_server(server,"VERIFY_RESIZE")
  2. Confirm the modification.
    conn.compute.confirm_server_resize(server)
  3. Roll back the modification. Rollback cannot be performed if you have already made the modification take effect.
    conn.compute.revert_server_resize(server)

Restarting an ECS

Use the following code to restart an ECS:

def reboot_server(conn): 
    conn.compute.reboot_server(server,'rebootType')

The rebootType value can be HARD or SOFT.

Stopping an ECS

Use the following code to stop an ECS:

def stop_server(conn): 
    conn.compute.stop_server(server)