rusoto_ec2_instance_connect/
generated.rs

1// =================================================================
2//
3//                           * WARNING *
4//
5//                    This file is generated!
6//
7//  Changes made to this file will be overwritten. If changes are
8//  required to the generated code, the service_crategen project
9//  must be updated to generate the changes.
10//
11// =================================================================
12
13use std::error::Error;
14use std::fmt;
15
16use async_trait::async_trait;
17use rusoto_core::credential::ProvideAwsCredentials;
18use rusoto_core::region;
19use rusoto_core::request::{BufferedHttpResponse, DispatchSignedRequest};
20use rusoto_core::{Client, RusotoError};
21
22use rusoto_core::proto;
23use rusoto_core::request::HttpResponse;
24use rusoto_core::signature::SignedRequest;
25#[allow(unused_imports)]
26use serde::{Deserialize, Serialize};
27
28impl Ec2InstanceConnectClient {
29    fn new_signed_request(&self, http_method: &str, request_uri: &str) -> SignedRequest {
30        let mut request = SignedRequest::new(
31            http_method,
32            "ec2-instance-connect",
33            &self.region,
34            request_uri,
35        );
36
37        request.set_content_type("application/x-amz-json-1.1".to_owned());
38
39        request
40    }
41
42    async fn sign_and_dispatch<E>(
43        &self,
44        request: SignedRequest,
45        from_response: fn(BufferedHttpResponse) -> RusotoError<E>,
46    ) -> Result<HttpResponse, RusotoError<E>> {
47        let mut response = self.client.sign_and_dispatch(request).await?;
48        if !response.status.is_success() {
49            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
50            return Err(from_response(response));
51        }
52
53        Ok(response)
54    }
55}
56
57use serde_json;
58#[derive(Clone, Debug, Default, PartialEq, Serialize)]
59#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
60pub struct SendSSHPublicKeyRequest {
61    /// <p>The availability zone the EC2 instance was launched in.</p>
62    #[serde(rename = "AvailabilityZone")]
63    pub availability_zone: String,
64    /// <p>The EC2 instance you wish to publish the SSH key to.</p>
65    #[serde(rename = "InstanceId")]
66    pub instance_id: String,
67    /// <p>The OS user on the EC2 instance whom the key may be used to authenticate as.</p>
68    #[serde(rename = "InstanceOSUser")]
69    pub instance_os_user: String,
70    /// <p>The public key to be published to the instance. To use it after publication you must have the matching private key.</p>
71    #[serde(rename = "SSHPublicKey")]
72    pub ssh_public_key: String,
73}
74
75#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
76#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
77pub struct SendSSHPublicKeyResponse {
78    /// <p>The request ID as logged by EC2 Connect. Please provide this when contacting AWS Support.</p>
79    #[serde(rename = "RequestId")]
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub request_id: Option<String>,
82    /// <p>Indicates request success.</p>
83    #[serde(rename = "Success")]
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub success: Option<bool>,
86}
87
88/// Errors returned by SendSSHPublicKey
89#[derive(Debug, PartialEq)]
90pub enum SendSSHPublicKeyError {
91    /// <p>Indicates that either your AWS credentials are invalid or you do not have access to the EC2 instance.</p>
92    Auth(String),
93    /// <p>Indicates that the instance requested was not found in the given zone. Check that you have provided a valid instance ID and the correct zone.</p>
94    EC2InstanceNotFound(String),
95    /// <p>Indicates that you provided bad input. Ensure you have a valid instance ID, the correct zone, and a valid SSH public key.</p>
96    InvalidArgs(String),
97    /// <p>Indicates that the service encountered an error. Follow the message's instructions and try again.</p>
98    Service(String),
99    /// <p>Indicates you have been making requests too frequently and have been throttled. Wait for a while and try again. If higher call volume is warranted contact AWS Support.</p>
100    Throttling(String),
101}
102
103impl SendSSHPublicKeyError {
104    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<SendSSHPublicKeyError> {
105        if let Some(err) = proto::json::Error::parse(&res) {
106            match err.typ.as_str() {
107                "AuthException" => {
108                    return RusotoError::Service(SendSSHPublicKeyError::Auth(err.msg))
109                }
110                "EC2InstanceNotFoundException" => {
111                    return RusotoError::Service(SendSSHPublicKeyError::EC2InstanceNotFound(
112                        err.msg,
113                    ))
114                }
115                "InvalidArgsException" => {
116                    return RusotoError::Service(SendSSHPublicKeyError::InvalidArgs(err.msg))
117                }
118                "ServiceException" => {
119                    return RusotoError::Service(SendSSHPublicKeyError::Service(err.msg))
120                }
121                "ThrottlingException" => {
122                    return RusotoError::Service(SendSSHPublicKeyError::Throttling(err.msg))
123                }
124                "ValidationException" => return RusotoError::Validation(err.msg),
125                _ => {}
126            }
127        }
128        RusotoError::Unknown(res)
129    }
130}
131impl fmt::Display for SendSSHPublicKeyError {
132    #[allow(unused_variables)]
133    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134        match *self {
135            SendSSHPublicKeyError::Auth(ref cause) => write!(f, "{}", cause),
136            SendSSHPublicKeyError::EC2InstanceNotFound(ref cause) => write!(f, "{}", cause),
137            SendSSHPublicKeyError::InvalidArgs(ref cause) => write!(f, "{}", cause),
138            SendSSHPublicKeyError::Service(ref cause) => write!(f, "{}", cause),
139            SendSSHPublicKeyError::Throttling(ref cause) => write!(f, "{}", cause),
140        }
141    }
142}
143impl Error for SendSSHPublicKeyError {}
144/// Trait representing the capabilities of the EC2 Instance Connect API. EC2 Instance Connect clients implement this trait.
145#[async_trait]
146pub trait Ec2InstanceConnect {
147    /// <p>Pushes an SSH public key to a particular OS user on a given EC2 instance for 60 seconds.</p>
148    async fn send_ssh_public_key(
149        &self,
150        input: SendSSHPublicKeyRequest,
151    ) -> Result<SendSSHPublicKeyResponse, RusotoError<SendSSHPublicKeyError>>;
152}
153/// A client for the EC2 Instance Connect API.
154#[derive(Clone)]
155pub struct Ec2InstanceConnectClient {
156    client: Client,
157    region: region::Region,
158}
159
160impl Ec2InstanceConnectClient {
161    /// Creates a client backed by the default tokio event loop.
162    ///
163    /// The client will use the default credentials provider and tls client.
164    pub fn new(region: region::Region) -> Ec2InstanceConnectClient {
165        Ec2InstanceConnectClient {
166            client: Client::shared(),
167            region,
168        }
169    }
170
171    pub fn new_with<P, D>(
172        request_dispatcher: D,
173        credentials_provider: P,
174        region: region::Region,
175    ) -> Ec2InstanceConnectClient
176    where
177        P: ProvideAwsCredentials + Send + Sync + 'static,
178        D: DispatchSignedRequest + Send + Sync + 'static,
179    {
180        Ec2InstanceConnectClient {
181            client: Client::new_with(credentials_provider, request_dispatcher),
182            region,
183        }
184    }
185
186    pub fn new_with_client(client: Client, region: region::Region) -> Ec2InstanceConnectClient {
187        Ec2InstanceConnectClient { client, region }
188    }
189}
190
191#[async_trait]
192impl Ec2InstanceConnect for Ec2InstanceConnectClient {
193    /// <p>Pushes an SSH public key to a particular OS user on a given EC2 instance for 60 seconds.</p>
194    async fn send_ssh_public_key(
195        &self,
196        input: SendSSHPublicKeyRequest,
197    ) -> Result<SendSSHPublicKeyResponse, RusotoError<SendSSHPublicKeyError>> {
198        let mut request = self.new_signed_request("POST", "/");
199        request.add_header(
200            "x-amz-target",
201            "AWSEC2InstanceConnectService.SendSSHPublicKey",
202        );
203        let encoded = serde_json::to_string(&input).unwrap();
204        request.set_payload(Some(encoded));
205
206        let response = self
207            .sign_and_dispatch(request, SendSSHPublicKeyError::from_response)
208            .await?;
209        let mut response = response;
210        let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
211        proto::json::ResponsePayload::new(&response).deserialize::<SendSSHPublicKeyResponse, _>()
212    }
213}