Loop through list of AWS-instances shows only first item

180 views Asked by At

I am working on a simple customer frontend for AWS. I want a list of all the users machines for start/stopping the EC2s. While the logic works I can only show the first of the machines in my view. I guess it's related to the AWS APIs pageable response format, which I don't fully understand.

I am trying to loop through the repsonse and use the index to generate instance variables to show in a table in my view. I only, ever get the first machine. Manually editing the value shows the proper machine, so it's in the repsonse array. How can I complete this list?

Here's my controller:

def ec2
 @instanz = User.myinstances(current_user.email)

  @instanz.reservations[0].instances.each_with_index do |response, index|
    @name = @instanz.reservations[0].instances[index].tags[0].value
    @state = @instanz.reservations[0].instances[index].state.name
    @ec2id = @instanz.reservations[0].instances[index].instance_id
  end

end

and the corresponding view:

<h3>Hier können Sie Ihre EC2-Instanzen starten und stoppen.</h3>


<%if @instanz %>

  <table width=100%>
  <th>Instanz-ID:</th><th>Name:</th><th>Status:</th><th>Aktion:</th>
  <tr>  <td><b><%= @ec2id %></b>  </td>
  <td> <%= @name %> </td>
    <td> <%= @state %> </td>

  <td> <%if @state == 'stopped' %>
  <%= button_to 'Starten', :action => 'startec2' %>
  <% else %>
  <%= button_to 'Stoppen', :action => 'stopec2' %>
</td>
  </tr>
  </table>
  <% end %> 

<% else %>
<h4>Es wurden leider keine EC2-Instanzen gefunden.<br>Wenn Sie glauben, dass es sich um einen Fehler handelt, setzen Sie sich bitte mit dem Support (Tel: -3333) in Verbindung. </h4>

<%end%>
1

There are 1 answers

4
rmagnum2002 On BEST ANSWER

As far as I know, the method in the controller will return the last object in the loop, so if you have 5 objects it will loop through each and will return the last one, cause that's where the controller method ends in your case.

You need to pass the array to the view and do a loop there.

def ec2
 @instanz = User.myinstances(current_user.email)
 @instances = @instanz.reservations[0].instances
end

view should be something like this:

<%if @instanz %>
  <table width=100%>
    <th>Instanz-ID:</th>
    <th>Name:</th>
    <th>Status:</th>
    <th>Aktion:</th>
    <% @instances.each do |i| %>
    <tr>
      <td><b><%= i.instance_id %></b></td>
      <td> <%= i.name %> </td>
      <td> <%= i.state.name %> </td>

      <td> <%if i.state.name == 'stopped' %>
        <%= button_to 'Starten', :action => 'startec2' %>
        <% else %>
        <%= button_to 'Stoppen', :action => 'stopec2' %>
      </td>
    </tr>
  </table>
<% else %>
  <h4>Es wurden leider keine EC2-Instanzen gefunden.<br>Wenn Sie glauben, dass es sich um einen Fehler handelt, setzen Sie sich bitte mit dem Support (Tel: -3333) in Verbindung. </h4>
<%end%>