Skip to main content

openstack_cli_load_balancer/v2/l7policy/
create.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//
13// SPDX-License-Identifier: Apache-2.0
14//
15// WARNING: This file is automatically generated from OpenAPI schema using
16// `openstack-codegenerator`.
17
18//! Create L7Policy command
19//!
20//! Wraps invoking of the `v2/lbaas/l7policies` with `POST` method
21
22use clap::Args;
23use eyre::WrapErr;
24use tracing::info;
25
26use openstack_cli_core::cli::CliArgs;
27use openstack_cli_core::error::OpenStackCliError;
28use openstack_cli_core::output::OutputProcessor;
29use openstack_sdk::AsyncOpenStack;
30
31use clap::ValueEnum;
32use openstack_sdk::api::QueryAsync;
33use openstack_sdk::api::load_balancer::v2::l7policy::create;
34use openstack_types::load_balancer::v2::l7policy::response;
35use serde_json::Value;
36
37/// Creates a L7 policy.
38///
39/// This operation provisions a new L7 policy by using the configuration that
40/// you define in the request object. After the API validates the request and
41/// starts the provisioning process, the API returns a response object that
42/// contains a unique ID and the status of provisioning the L7 policy.
43///
44/// In the response, the L7 policy [provisioning status](#prov-status) is
45/// `ACTIVE`, `PENDING_CREATE`, or `ERROR`.
46///
47/// If the status is `PENDING_CREATE`, issue GET
48/// `/v2/lbaas/l7policies/{l7policy_id}` to view the progress of the
49/// provisioning operation. When the L7 policy status changes to `ACTIVE`, the
50/// L7 policy is successfully provisioned and is ready for further
51/// configuration.
52///
53/// If the API cannot fulfill the request due to insufficient data or data that
54/// is not valid, the service returns the HTTP `Bad Request (400)` response
55/// code with information about the failure in the response body. Validation
56/// errors require that you correct the error and submit the request again.
57///
58/// All the rules associated with a given policy are logically ANDead together.
59/// A request must match all the policy’s rules to match the policy.
60///
61/// If you need to express a logical OR operation between rules, then do this
62/// by creating multiple policies with the same action.
63///
64/// If a new policy is created with a position that matches that of an existing
65/// policy, then the new policy is inserted at the given position.
66///
67/// L7 policies with `action` of `REDIRECT_TO_URL` will return the default HTTP
68/// `Found (302)` response code with the `redirect_url`. Also, specify
69/// `redirect_http_code` to configure the needed HTTP response code, such as,
70/// 301, 302, 303, 307 and 308.
71///
72/// L7 policies with `action` of `REJECT` will return a `Forbidden (403)`
73/// response code to the requester.
74#[derive(Args)]
75#[command(about = "Create an L7 Policy")]
76pub struct L7PolicyCommand {
77    /// Request Query parameters
78    #[command(flatten)]
79    query: QueryParameters,
80
81    /// Path parameters
82    #[command(flatten)]
83    path: PathParameters,
84
85    /// Defines mandatory and optional attributes of a POST request.
86    #[command(flatten)]
87    l7policy: L7policy,
88}
89
90/// Query parameters
91#[derive(Args)]
92struct QueryParameters {}
93
94/// Path parameters
95#[derive(Args)]
96struct PathParameters {}
97
98#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
99enum Action {
100    RedirectPrefix,
101    RedirectToPool,
102    RedirectToUrl,
103    Reject,
104}
105
106/// L7policy Body data
107#[derive(Args, Clone)]
108struct L7policy {
109    /// The L7 policy action. One of `REDIRECT_PREFIX`, `REDIRECT_TO_POOL`,
110    /// `REDIRECT_TO_URL`, or `REJECT`.
111    #[arg(help_heading = "Body parameters", long)]
112    action: Action,
113
114    /// The administrative state of the resource, which is up (`true`) or down
115    /// (`false`). Default is `true`.
116    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
117    admin_state_up: Option<bool>,
118
119    /// A human-readable description for the resource.
120    #[arg(help_heading = "Body parameters", long)]
121    description: Option<String>,
122
123    /// The ID of the listener.
124    #[arg(help_heading = "Body parameters", long)]
125    listener_id: String,
126
127    /// Human-readable name of the resource.
128    #[arg(help_heading = "Body parameters", long)]
129    name: Option<String>,
130
131    /// The position of this policy on the listener. Positions start at 1.
132    #[arg(help_heading = "Body parameters", long)]
133    position: Option<i32>,
134
135    /// The ID of the project owning this resource.
136    #[arg(help_heading = "Body parameters", long)]
137    project_id: Option<String>,
138
139    /// Requests matching this policy will be redirected to the specified URL
140    /// or Prefix URL with the HTTP response code. Valid if `action` is
141    /// `REDIRECT_TO_URL` or `REDIRECT_PREFIX`. Valid options are: 301, 302,
142    /// 303, 307, or 308. Default is 302.
143    ///
144    /// **New in version 2.9**
145    #[arg(help_heading = "Body parameters", long)]
146    redirect_http_code: Option<i32>,
147
148    /// Requests matching this policy will be redirected to the pool with this
149    /// ID. Only valid if `action` is `REDIRECT_TO_POOL`. The pool has some
150    /// restrictions, See
151    /// [Protocol Combinations (Listener/Pool)](#valid-protocol).
152    #[arg(help_heading = "Body parameters", long)]
153    redirect_pool_id: Option<String>,
154
155    /// Requests matching this policy will be redirected to this Prefix URL.
156    /// Only valid if `action` is `REDIRECT_PREFIX`.
157    #[arg(help_heading = "Body parameters", long)]
158    redirect_prefix: Option<String>,
159
160    /// Requests matching this policy will be redirected to this URL. Only
161    /// valid if `action` is `REDIRECT_TO_URL`.
162    #[arg(help_heading = "Body parameters", long)]
163    redirect_url: Option<String>,
164
165    /// Parameter is an array, may be provided multiple times.
166    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="JSON", value_parser=openstack_cli_core::common::parse_json)]
167    rules: Option<Vec<Value>>,
168
169    /// Parameter is an array, may be provided multiple times.
170    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
171    tags: Option<Vec<String>>,
172
173    #[arg(help_heading = "Body parameters", long)]
174    tenant_id: Option<String>,
175}
176
177impl L7PolicyCommand {
178    /// Perform command action
179    pub async fn take_action<C: CliArgs>(
180        &self,
181        parsed_args: &C,
182        client: &mut AsyncOpenStack,
183    ) -> Result<(), OpenStackCliError> {
184        info!("Create L7Policy");
185
186        let op =
187            OutputProcessor::from_args(parsed_args, Some("load-balancer.l7policy"), Some("create"));
188        op.validate_args(parsed_args)?;
189
190        let mut ep_builder = create::Request::builder();
191
192        // Set body parameters
193        // Set Request.l7policy data
194        let args = &self.l7policy;
195        let mut l7policy_builder = create::L7policyBuilder::default();
196
197        let tmp = match &args.action {
198            Action::RedirectPrefix => create::Action::RedirectPrefix,
199            Action::RedirectToPool => create::Action::RedirectToPool,
200            Action::RedirectToUrl => create::Action::RedirectToUrl,
201            Action::Reject => create::Action::Reject,
202        };
203        l7policy_builder.action(tmp);
204
205        if let Some(val) = &args.admin_state_up {
206            l7policy_builder.admin_state_up(*val);
207        }
208
209        if let Some(val) = &args.description {
210            l7policy_builder.description(val);
211        }
212
213        l7policy_builder.listener_id(&args.listener_id);
214
215        if let Some(val) = &args.name {
216            l7policy_builder.name(val);
217        }
218
219        if let Some(val) = &args.position {
220            l7policy_builder.position(*val);
221        }
222
223        if let Some(val) = &args.project_id {
224            l7policy_builder.project_id(val);
225        }
226
227        if let Some(val) = &args.redirect_http_code {
228            l7policy_builder.redirect_http_code(*val);
229        }
230
231        if let Some(val) = &args.redirect_pool_id {
232            l7policy_builder.redirect_pool_id(val);
233        }
234
235        if let Some(val) = &args.redirect_prefix {
236            l7policy_builder.redirect_prefix(val);
237        }
238
239        if let Some(val) = &args.redirect_url {
240            l7policy_builder.redirect_url(val);
241        }
242
243        if let Some(val) = &args.rules {
244            let rules_builder: Vec<create::Rules> = val
245                .iter()
246                .flat_map(|v| serde_json::from_value::<create::Rules>(v.to_owned()))
247                .collect::<Vec<create::Rules>>();
248            l7policy_builder.rules(rules_builder);
249        }
250
251        if let Some(val) = &args.tags {
252            l7policy_builder.tags(val.iter().map(Into::into).collect::<Vec<_>>());
253        }
254
255        if let Some(val) = &args.tenant_id {
256            l7policy_builder.tenant_id(val);
257        }
258
259        ep_builder.l7policy(
260            l7policy_builder
261                .build()
262                .wrap_err("error preparing the request data")?,
263        );
264
265        let ep = ep_builder
266            .build()
267            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
268
269        let data: serde_json::Value = ep.query_async(client).await?;
270
271        op.output_single::<response::create::L7policyResponse>(data.clone())?;
272        // Show command specific hints
273        op.show_command_hint()?;
274        Ok(())
275    }
276}