how do I create amazon ec2 instance with iam profile via php? - amazon-ec2

I'd like to know how to create a new amazon ec2 instance using the php sdk and to do so providing it a IAM profile for a given role upon startup.
This is a new feature apparently, and consequently the real world examples are sparse at this time. Any help would be appreciated, the link from Amazon below is tempting, but skips over the part of actually creating the instance with a IAM profile assigned from SDK and instead uses the management console (which defeats the whole purpose, right?).
http://docs.amazonwebservices.com/AWSSdkDocsPHP/latest/DeveloperGuide/php-dg-roles.html
I'm assuming its an option of run_instances, but i suppose it could be via IAM object instead?
Thanks,
R

Ok, here is the SDK Answer based on what ended up working for me:
$options = array(
'InstanceType'=>$this->instance_size,
'KeyName'=>'my key',
'SecurityGroup'=>'mysecgroup',
'UserData' => base64_encode($user_data_contents),
'Placement' => array(
'AvailabilityZone' => $this->availability_zone
),
'IamInstanceProfile' => array(
'Arn' => 'arn:aws:iam::9999999999999:instance-profile/yourIAMNameHere'
)
);
Not a particular hard answer in retrospect - I include here to help get the SDK documentation pumped up a bit since this is a new function for EC2

Related

How can I call list of ec2 instance based on the app code using tag method

I am trying to get all the instance(server name) ID based on the app. Let's say I have an app in the server. How do I know which apps below to which server. I want my code to find all the instance (server) that belongs to each app. Is there any way to look through the app in the ec2 console and figure out the servers are associated with the app. More of using tag method
import boto3
client = boto3.client('ec2')
my_instance = 'i-xxxxxxxx'
(Disclaimer: I work for AWS Resource Groups)
Seeing your comments that you use tags for all apps, you can use AWS Resource Groups to create a group - the example below assumes you used App:Something as tag, first creates a Resource Group, and then lists all the members of that group.
Using this group, you can for example get automatically a CloudWatch dashboard for those resources, or use this group as a target in RunCommand.
import json
import boto3
RG = boto3.client('resource-groups')
RG.create_group(
Name = 'Something-App-Instances',
Description = 'EC2 Instances for Something App',
ResourceQuery = {
'Type': 'TAG_FILTERS_1_0',
'Query': json.dumps({
'ResourceTypeFilters': ['AWS::EC2::Instance'],
'TagFilters': [{
'Key': 'App',
'Values': ['Something']
}]
})
},
Tags = {
'App': 'Something'
}
)
# List all resources in a group using a paginator
paginator = RG.get_paginator('list_group_resources')
resource_pages = paginator.paginate(GroupName = 'Something-App-Instances')
for page in resource_pages:
for resource in page['ResourceIdentifiers']:
print(resource['ResourceType'] + ': ' + resource['ResourceArn'])
Another option to just get the list without saving it as a group would be to directly use the Resource Groups Tagging API
What you install on an Amazon EC2 instance is totally up to you. You do this by running code on the instance itself. AWS is not involved in the decision of what you install on the instance, nor does it know what you installed on an instance.
Therefore, you will need to keep track of "what apps are installed on what server" yourself.
You might choose to take advantage of Tags on instances to add some metadata, such as the purpose of the server. You could also use AWS Systems Manager to run commands on instances (eg to install software) or even use AWS CodeDeploy to roll-out software to fleets of servers.
However, even with all of these deployment options, AWS cannot track what you have put on each individual server. You will need to do that yourself.
Update: You can use AWS Resource Groups to view/manage resources by tag.
Here's some sample Python code to list tags by instance:
import boto3
ec2_resource = boto3.resource('ec2', region_name='ap-southeast-2')
instances = ec2_resource.instances.all()
for instance in instances:
for tag in instance.tags:
print(instance.instance_id, tag['Key'], tag['Value'])

Permissions error: Connect to Business Manager to Create This Audience while creating facebook custom audience using ruby sdk

I am trying to create custom audience using facebook-ruby-business-sdk. I am using below code,
require 'facebook_ads'
ad_acc = FacebookAds::AdAccount.get('act_351195241', 'name', {
access_token: "<USER_ACCESS_TOKEN>", app_secret: "<APP_SECRET_KEY>"
})
ca = ad_acc.customaudiences.create({
name: 'Customers from CRM',
subtype: 'CUSTOM',
description: 'CA from API',
customer_file_source: 'USER_PROVIDED_ONLY',
})
users = [['FirstName', 'test1#example.com', 'LastName1'],
['FirstNameTest', 'test2#example.com', 'LastNameTest']]
schema = ["FN","EMAIL","LN"]
ca.add_user(users, schema)
And I am getting this error Permissions error: Connect to Business Manager to Create This Audience whereas I have already created a business manager account and attached this to it.
I am struck here and it would be great if anyone can help me out in this.
Could not find place to add higher level permission. Is it adding ads_read and ads_management access under Marketing API settings? IS THIS the ONE?

Accessing entire netflix catalog via API v1.5

Netflix recently updated their API methods for obtaining the full Netflix catalog. I'm curious if anyone has had any success accessing these new xml documents and downloading them via API v1.5 (9/2012). Previously, you could download the entire Netflix catalog via one API call (which I had working perfectly). Now, there are supposedly two calls to make: one for dvd's and one for streaming movies.
I cannot make these calls return anything except for an empty array. Please don't offer an answer unless you have personally downloaded the entire catalog via these new API's.
Bonus points if you can tell me how to do it in Ruby.
http://developer.netflix.com/blog/read/Update_Changes_for_the_Public_API
This did it for me (download the netflix instant cat)...it's in php but can prob be easily rewritten in ruby..this is using JR Collings OAuthsimple
args = Array(
max_results=> 20,
start_index=>0
);
//args don't matter, netflix doesn't listen here
// this is the URL path (note the lack of arguments.)
$rpath = "http://api-public.netflix.com/catalog/titles/streaming";
// Create the Signature object.
$roauth = new OAuthSimple();
$rsigned = $roauth->sign(Array(path=>$rpath,
parameters=>$args,
signatures=> Array('consumer_key'=>YOURKEY,
'shared_secret'=>YOURSECRET,
)));
$getxml = file_get_contents($rsigned['signed_url']);
file_put_contents("streaming.xml", $getxml);

Timeout Problem with Ruby Fog when bootstrapping AWS servers

I've been trying for a little while now to provision a small instance on AWS with the fog library. I've been somewhat successful (in that an instance does spool up when I run this code), but I keep getting timeout errors during the SSH portion, and when I dug deeper I found that they're consistently "AuthentitcationFailed" problems.
The failing code is as follows:
require 'rubygems'
require "fog"
connection = Fog::Compute.new({
provider: "AWS",
aws_secret_access_key: SECRET_KEY,
aws_access_key_id: ACCESS_KEY
})
server = connection.servers.bootstrap({
private_key_path: "~/.ssh/id_rsa",
public_key_path: "~/.ssh/id_rsa.pub",
username: "ubuntu"
})
Much reading has told me that sometimes this is just because the instance takes too long to spool up, but this is very consistent (it happens every time I try it). Does anyone see what I'm doing wrong?
I had the same problem some days ago and actually found the problem for my case and submitted it to the Fog issue tracker.
A colleague of mine was using connection.bootstrap() with the same AWS credentials but different SSH keys. So the "fog_default" public key had already been registered and the attempt to log in with my key pair failed.
If you're experiencing similar problems, check with connection.key_pairs.get('fog_default') if fog_default was registered before.
If this is actually the case, you have three options to get around this problem:
Delete the fog_default by running: connection.key_pairs.get('fog_default').destroy and register your new public key via bootstrap()
Manually register your custom key under a custom name
Set Fog.credential to a custom name so bootstrap() uses this name instead of "default" to register your public key
Solution two looks like this:
Fog.credentials = Fog.credentials.merge({
:private_key_path => "./keys/my_custom_key",
:public_key_path => "./keys/my_custom_key.pub"
})
if connection.key_pairs.get('my_custom_key').nil?
public_key = IO.read('./keys/my_custom_key.pub')
connection.import_key_pair('my_custom_key', public_key)
end
server = connection.servers.bootstrap(
:key_name => 'my_custom_key',
...
)
Solution three, which I prefer because the only change I need to make is to set Fog.credential, looks like this:
Fog.credential = :my_custom_key
connection.servers.bootstrap(
:private_key_path => './keys/my_custom_key',
:public_key_path => './keys/my_custom_key.pub',
...
)
I'd recommend a few things to diagnose the problem (if you're still having it)
Check your security groups to make sure port 22 is open to your IP / the world (0.0.0.0/0)
Try connecting manually using SSH
If you still see issues, try
ssh -v -v <normal options>
This will give you more information on what is happening when trying to connect to the instance.

Is it possible to post a comment to an existing Event using php-sdk?

I'm able to create and delete events, but haven't found where to post follow-up comments to events.
So, is it even possible to post a comment to an existing event, created by my application, using php-sdk?
I am assuming that you meant "make a post on a event wall" because you can not comment events in Facebook. You can use the PHP SDK (see on github) to make any call on the graph API, including posting on an event wall.
You need for that the access token of your application (see how to get it in the Facebook reference) and the ID of the event (EVENT_ID). And then :
require "facebook.php";
$facebook = new Facebook(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
);
$facebook->setAccessToken(YOUR_APP_TOKEN);
$args['message'] = "Hello world !";
$facebook->api('/EVENT_ID/feed', $args);
More on publishing post in the Facebook graph API Documentation.
Hope that helps !

Resources