简体   繁体   中英

How do I replicate these shell commands in Ruby aws-sdk for switching elastic IPs?

I've got elastic IP switching set up on my AWS Linux box. I know the shell commands to switch IP addresses. But I don't know how to do this in Ruby.

Here's the shell commands...

  1. Get Instance ID:

    wget -O - ' http://MY.AWS.IP.HERE/latest/meta-data/instance-id ' 2>/dev/null

  2. Allocate an elastic IP:

    aws ec2 allocate-address

  3. Associate elastic IP with this instance. Use instance and allocation IDs returned from steps 1 and 2.

    aws ec2 associate-address --instance-id INSTANCE_ID_HERE --allocation-id ALLOCATION_ID_HERE

How do I do these with Ruby's aws-sdk gem?

UPDATE

Here's my code now

require 'aws-sdk'
require 'json'
require 'pp'

region = 'REGION NAME'
aws_access_key_id = 'SECRET KEY ID'
aws_secret_access_key = 'SECRET ACCESS KEY'
credentials = Aws::Credentials.new(aws_access_key_id, aws_secret_access_key)
client = Aws::EC2::Client.new(
    region: region,
    credentials: credentials
)
pp client
p '==='

describeAddresses = `aws ec2 describe-addresses`
awsHash = JSON.parse(describeAddresses)
pp awsHash
p '==='

getInstanceID = `wget -O - 'http://MY.AWS.IP.HERE/latest/meta-data/instance-id' 2>/dev/null`
instanceID = getInstanceID.split("\n")[-1]
pp instanceID
p '==='

resp = client.allocate_address({
  domain: "vpc", # accepts vpc, standard
})
pp resp
p '==='

resp2 = client.associate_address({
    instance_id: instanceID,
    allocation_id: resp['allocation_id'],
    allow_reassociation: true#,
})
pp resp2
p '==='

Changes IP, but now I get kicked from XShell when I execute the code. But that's for a different question.

1) you can issue the command in ruby directly and grab the output or you can use httpclient or other lib that can do http requests

2) use allocate_address-instance

3) use associate_address

for 2) and 3) you need to use the AWS Ruby SDK . There's almost a 1:1 mapping between what you're doing in cmd line and what the api calls are

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM