def delete_route_from_main_route_table(ec2_client, main_route_table_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.delete_route response = ec2_client.delete_route( DestinationCidrBlock='0.0.0.0/0', RouteTableId=main_route_table_id, ) print_response(inspect.getframeinfo(inspect.currentframe())[2], response)
def modify_vpc_attribute(ec2_client, vpc_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.modify_vpc_attribute response = ec2_client.modify_vpc_attribute( EnableDnsHostnames={'Value': True}, VpcId=vpc_id, ) print_response(inspect.getframeinfo(inspect.currentframe())[2], response)
def create_route_in_route_table(ec2_resource, route_table_id, internet_gateway_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.RouteTable.create_route route_table = ec2_resource.RouteTable(route_table_id) route = route_table.create_route( DestinationCidrBlock='0.0.0.0/0', GatewayId=internet_gateway_id, ) print_response(inspect.getframeinfo(inspect.currentframe())[2], route)
def associate_route_table_with_subnet(ec2_resource, route_table_id, subnet_id): # clientとresourceのどちらでもできるが、resourceのほうがオブジェクトが返ってきて扱いやすい # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.associate_route_table # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.RouteTable.associate_with_subnet route_table = ec2_resource.RouteTable(route_table_id) route_table_association = route_table.associate_with_subnet(SubnetId=subnet_id) print_response(inspect.getframeinfo(inspect.currentframe())[2], route_table_association) return route_table_association.route_table_association_id
def create_nat_gateway(ec2_client, allocation_id, subnet_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.create_nat_gateway response = client.create_nat_gateway( AllocationId=allocation_id, SubnetId=subnet_id, ) print_response(inspect.getframeinfo(inspect.currentframe())[2], response) return response['NatGateway']['NatGatewayId']
def create_security_group(ec2_client, vpc_id, name): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.create_security_group response = ec2_client.create_security_group( Description=name, GroupName=name, VpcId=vpc_id, ) print_response(inspect.getframeinfo(inspect.currentframe())[2], response) return response['GroupId']
def create_subnet_name_tag(ec2_subnet, subnet_name): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Subnet.create_tags tag = ec2_subnet.create_tags( Tags=[{ 'Key': 'Name', 'Value': subnet_name, }] ) print_response(inspect.getframeinfo(inspect.currentframe())[2], tag)
def create_vpc(ec2_client): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.create_vpc response = ec2_client.create_vpc( CidrBlock='192.168.0.0/16', AmazonProvidedIpv6CidrBlock=False, ) vpc_id = response['Vpc']['VpcId'] print_response(inspect.getframeinfo(inspect.currentframe())[2], vpc_id) return vpc_id
def authorize_ingress_by_http_port(ec2_resource, security_group_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.SecurityGroup.authorize_ingress security_group = ec2_resource.SecurityGroup(security_group_id) response = security_group.authorize_ingress( CidrIp='0.0.0.0/0', IpProtocol='tcp', FromPort=80, ToPort=80, ) print_response(inspect.getframeinfo(inspect.currentframe())[2], response)
def describe_availability_zones(ec2_client): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_availability_zones response = ec2_client.describe_availability_zones( Filters=[{ 'Name': 'state', 'Values': ['available'], }] ) print_response(inspect.getframeinfo(inspect.currentframe())[2], response) return response
def attach_internet_gateway_to_vpc(ec2_resource, internet_gateway_id, vpc_id): # clientとresourceのどちらでもできるが、resourceのほうがオブジェクトが返ってきて扱いやすい # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.attach_internet_gateway # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.InternetGateway.attach_to_vpc internet_gateway = ec2_resource.InternetGateway(internet_gateway_id) response = internet_gateway.attach_to_vpc( VpcId=vpc_id, ) print_response(inspect.getframeinfo(inspect.currentframe())[2], response) return response
def create_internet_gateway_name_tag(ec2_resource, internet_gateway_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.InternetGateway.create_tags internet_gateway = ec2_resource.InternetGateway(internet_gateway_id) tags = internet_gateway.create_tags( Tags=[{ 'Key': 'Name', 'Value': 'インターネットゲートウェイ2', }] ) print_response(inspect.getframeinfo(inspect.currentframe())[2], tags)
def wait_nat_gateway_available(ec2_client, nat_gateway_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Waiter.NatGatewayAvailable print(f'NAT Gatewayがavailableになるまで待つ(開始):{datetime.datetime.now()}') waiter = ec2_client.get_waiter('nat_gateway_available') response = waiter.wait(Filters=[{ 'Name': 'state', 'Values': ['available'] }], NatGatewayIds=[nat_gateway_id]) print_response(inspect.getframeinfo(inspect.currentframe())[2], response) print(f'NAT Gatewayがavailableになるまで待つ(終了):{datetime.datetime.now()}')
def create_route_table_tag_name(ec2_resource, route_table_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#routetable route_table = ec2_resource.RouteTable(route_table_id) # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.RouteTable.create_tags tag = route_table.create_tags( Tags=[{ 'Key': 'Name', 'Value': 'パブリックルートテーブル2', }] ) print_response(inspect.getframeinfo(inspect.currentframe())[2], tag)
def create_vpc_subnet(ec2_resource, vpc_id, availability_zone, cidr_block): # clientとresourceのどちらでもできるが、resourceのほうがオブジェクトが返ってきて扱いやすい # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.create_subnet # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Vpc.create_subnet vpc = ec2_resource.Vpc(vpc_id) response = vpc.create_subnet( AvailabilityZone=availability_zone, CidrBlock=cidr_block, ) print_response(inspect.getframeinfo(inspect.currentframe())[2], response) # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Subnet return response
def add_vpc_name_tag(ec2_resource, vpc_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Vpc.create_tags vpc = ec2_resource.Vpc(vpc_id) tag = vpc.create_tags( Tags=[ { 'Key': 'Name', 'Value': 'VPC領域2' }, ] ) print_response(inspect.getframeinfo(inspect.currentframe())[2], tag)
def describe_main_route_tables(ec2_client, vpc_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_route_tables response = ec2_client.describe_route_tables(Filters=[{ 'Name': 'association.main', 'Values': ['true'], }, { 'Name': 'vpc-id', 'Values': [vpc_id], }]) main_route_table_id = response['RouteTables'][0]['RouteTableId'] print_response( inspect.getframeinfo(inspect.currentframe())[2], main_route_table_id) return main_route_table_id
def print_info(self): print('[Governance]') print_response('version', self.get_version()) print_response('revision', self.get_revision()) step_price = self.get_step_price() print(f'"stepPrice": {step_price} ({int(step_price, 16)})') max_step_limits = { "invoke": self.get_max_step_limit("invoke"), "query": self.get_max_step_limit("query") } print_response('stepLimit', max_step_limits) print_response('stepCosts', self.get_step_costs()) print_response('serviceConfig', self.get_service_config())
def describe_vpc(ec2_client): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_vpcs # VPC名でフィルタ response = ec2_client.describe_vpcs( Filters=[ { 'Name': 'tag:Name', 'Values': [ 'VPC領域', ] } ] ) print_response(inspect.getframeinfo(inspect.currentframe())[2], response)
def terminate_instances_with_wait(ec2_client, instance_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.terminate_instances response = ec2_client.terminate_instances(InstanceIds=[instance_id]) print_response(inspect.getframeinfo(inspect.currentframe())[2], response) # インスタンスが削除されるのを待つ # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Waiter.InstanceTerminated waiter = ec2_client.get_waiter('instance_terminated') waiter.wait( Filters=[{ 'Name': 'instance-state-name', 'Values': ['terminated'], }], InstanceIds=[instance_id], )
def create_ec2_instances( ec2_resource, security_group_id, subnet_id, key_pair_name, is_associate_public_ip, private_ip, instance_name): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#service-resource # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances response = ec2_resource.create_instances( ImageId=IMAGE_ID, # 無料枠はt2.micro InstanceType='t2.micro', # 事前に作ったキー名を指定 KeyName=key_pair_name, # インスタンス数は、最大・最小とも1にする MaxCount=1, MinCount=1, # モニタリングはデフォルト = Cloud Watchは使わないはず # Monitoring={'Enabled': False}, # サブネットにavailability zone が結びついてるので、明示的なセットはいらないかも # Placement={'AvailabilityZone': availability_zone}, # セキュリティグループIDやサブネットIDはNetworkInterfacesでセット(詳細は以下) # SecurityGroupIds=[security_group_id], # SubnetId=subnet_id, NetworkInterfaces=[{ # 自動割り当てパブリックIP 'AssociatePublicIpAddress': is_associate_public_ip, # デバイスインタフェースは1つだけなので、最初のものを使う 'DeviceIndex': 0, # セキュリティグループIDは、NetworkInterfacesの方で割り当てる # インスタンスの方で割り当てると以下のエラー: # Network interfaces and an instance-level security groups may not be specified on the same request 'Groups': [security_group_id], # プライベートIPアドレス 'PrivateIpAddress': private_ip, # サブネットIDも、NetworkInterfacesの方で割り当てる # インスタンスの方で割り当てると以下のエラー: # Network interfaces and an instance-level subnet ID may not be specified on the same request 'SubnetId': subnet_id, }], TagSpecifications=[{ 'ResourceType': 'instance', 'Tags': [{ 'Key': 'Name', 'Value': instance_name, }] }], ) print_response(inspect.getframeinfo(inspect.currentframe())[2], response) # EC2インスタンスは1つだけ生成しているので、そのインスタンスを戻り値にする return response[0]
def _check_and_set(self, wallet, address, current_stake, auto_staking): balance = self.balance(address) status = { 'staked': in_icx(current_stake), 'unstaked': in_icx(balance), } total_icx = in_icx(current_stake + balance) print_response('Balance (in ICX)', status) print('Total ICX balance =', total_icx) if auto_staking: new_amount = int(total_icx - 1.0) # leave 1.0 ICX for future transactions else: input_value = input('\n==> New staking amount (in ICX)? ') new_amount = self._check_value(input_value, int(total_icx)) self._check_total_delegated(address, in_loop(new_amount)) print('Requested amount =', new_amount, f'({in_loop(new_amount)} loop)') tx_hash = self.set(wallet, new_amount) self._ensure_tx_result(tx_hash, auto_staking)
session = boto3.Session(profile_name='my-profile') # 使用するクライアントとリソースを作成 client = create_ec2_client(session) resource = create_ec2_resource(session) # VPCの作成と確認 aws['vpc_id'] = create_vpc(client) add_vpc_name_tag(resource, aws['vpc_id']) describe_vpc(client) # サブネットの作成 # アベイラビリティゾーンの確認 zones = describe_availability_zones(client) # 最初のアベイラビリティゾーンを使用するアベイラビリティゾーンとする first_zone = zones['AvailabilityZones'][0]['ZoneName'] print_response('first availability zone', first_zone) subnet = create_vpc_subnet(resource, aws['vpc_id'], first_zone, '192.168.1.0/24') aws['public_subnet_id'] = subnet.subnet_id # サブネットの名前タグを追加 create_subnet_name_tag(subnet, 'パブリックサブネット2') # インターネットゲートウェイの作成 aws['internet_gateway_id'] = create_internet_gateway(client) # インターネットゲートウェイの名前をつける create_internet_gateway_name_tag(resource, aws['internet_gateway_id']) # インターネットゲートウェイをVPC領域に結びつける attach_internet_gateway_to_vpc(resource, aws['internet_gateway_id'], aws['vpc_id']) # ルートテーブルの設定 # ルートテーブルの作成 aws['public_route_table_id'] = create_route_table(client, aws['vpc_id'])
def create_internet_gateway(ec2_client): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.create_internet_gateway response = ec2_client.create_internet_gateway() print_response(inspect.getframeinfo(inspect.currentframe())[2], response) return response['InternetGateway']['InternetGatewayId']
def delete_security_group(ec2_client, group_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.delete_security_group response = ec2_client.delete_security_group(GroupId=group_id) print_response(inspect.getframeinfo(inspect.currentframe())[2], response)
def delete_subnet(ec2_client, subnet_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.delete_subnet response = ec2_client.delete_subnet(SubnetId=subnet_id) print_response(inspect.getframeinfo(inspect.currentframe())[2], response)
def delete_key_pair(ec2_client, key_pair_name): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.delete_key_pair response = ec2_client.delete_key_pair(KeyName=key_pair_name) print_response(inspect.getframeinfo(inspect.currentframe())[2], response)
def describe_route_tables(ec2_client): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_route_tables response = ec2_client.describe_route_tables() print_response(inspect.getframeinfo(inspect.currentframe())[2], response)
def print_status(address, result): print('[Stake]') print_response(address, result) print('StakedICX =', in_icx(int(result['stake'], 16)))
def create_route_table(ec2_client, vpc_id): # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.create_route_table response = ec2_client.create_route_table(VpcId=vpc_id) route_table_id = response['RouteTable']['RouteTableId'] print_response(inspect.getframeinfo(inspect.currentframe())[2], route_table_id) return route_table_id