Skip to main content

openstack_cli_load_balancer/v2/l7policy/rule/
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 Rule command
19//!
20//! Wraps invoking of the `v2/lbaas/l7policies/{l7policy_id}/rules` 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::rule::create;
34use openstack_types::load_balancer::v2::l7policy::rule::response;
35
36/// Creates a L7 rule.
37///
38/// This operation provisions a new L7 rule by using the configuration that you
39/// define in the request object. After the API validates the request and
40/// starts the provisioning process, the API returns a response object that
41/// contains a unique ID and the status of provisioning the L7 rule.
42///
43/// In the response, the L7 rule [provisioning status](#prov-status) is
44/// `ACTIVE`, `PENDING_CREATE`, or `ERROR`.
45///
46/// If the status is `PENDING_CREATE`, issue GET
47/// `/v2/lbaas/l7policies/{l7policy_id}/rules/{l7rule_id}` to view the progress
48/// of the provisioning operation. When the L7 rule status changes to `ACTIVE`,
49/// the L7 rule is successfully provisioned and is ready for further
50/// configuration.
51///
52/// If the API cannot fulfill the request due to insufficient data or data that
53/// is not valid, the service returns the HTTP `Bad Request (400)` response
54/// code with information about the failure in the response body. Validation
55/// errors require that you correct the error and submit the request again.
56///
57/// All the rules associated with a given policy are logically ANDead together.
58/// A request must match all the policy’s rules to match the policy.
59///
60/// If you need to express a logical OR operation between rules, then do this
61/// by creating multiple policies with the same action.
62#[derive(Args)]
63#[command(about = "Create an L7 Rule")]
64pub struct RuleCommand {
65    /// Request Query parameters
66    #[command(flatten)]
67    query: QueryParameters,
68
69    /// Path parameters
70    #[command(flatten)]
71    path: PathParameters,
72
73    /// Defines mandatory and optional attributes of a POST request.
74    #[command(flatten)]
75    rule: Rule,
76}
77
78/// Query parameters
79#[derive(Args)]
80struct QueryParameters {}
81
82/// Path parameters
83#[derive(Args)]
84struct PathParameters {
85    /// l7policy_id parameter for
86    /// /v2/lbaas/l7policies/{l7policy_id}/rules/{rule_id} API
87    #[arg(
88        help_heading = "Path parameters",
89        id = "path_param_l7policy_id",
90        value_name = "L7POLICY_ID"
91    )]
92    l7policy_id: String,
93}
94
95#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
96enum CompareType {
97    Contains,
98    EndsWith,
99    EqualTo,
100    Regex,
101    StartsWith,
102}
103
104#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
105enum Type {
106    Cookie,
107    FileType,
108    Header,
109    HostName,
110    Path,
111    SslConnHasCert,
112    SslDnField,
113    SslVerifyResult,
114}
115
116/// Rule Body data
117#[derive(Args, Clone)]
118struct Rule {
119    /// The administrative state of the resource, which is up (`true`) or down
120    /// (`false`). Default is `true`.
121    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
122    admin_state_up: Option<bool>,
123
124    /// The comparison type for the L7 rule. One of `CONTAINS`, `ENDS_WITH`,
125    /// `EQUAL_TO`, `REGEX`, or `STARTS_WITH`.
126    #[arg(help_heading = "Body parameters", long)]
127    compare_type: CompareType,
128
129    /// When `true` the logic of the rule is inverted. For example, with invert
130    /// `true`, equal to would become not equal to. Default is `false`.
131    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
132    invert: Option<bool>,
133
134    /// The key to use for the comparison. For example, the name of the cookie
135    /// to evaluate.
136    #[arg(help_heading = "Body parameters", long)]
137    key: Option<String>,
138
139    /// The ID of the project owning this resource.
140    #[arg(help_heading = "Body parameters", long)]
141    project_id: Option<String>,
142
143    /// A list of simple strings assigned to the resource.
144    ///
145    /// **New in version 2.5**
146    ///
147    /// Parameter is an array, may be provided multiple times.
148    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
149    tags: Option<Vec<String>>,
150
151    #[arg(help_heading = "Body parameters", long)]
152    tenant_id: Option<String>,
153
154    /// The L7 rule type. One of `COOKIE`, `FILE_TYPE`, `HEADER`, `HOST_NAME`,
155    /// `PATH`, `SSL_CONN_HAS_CERT`, `SSL_VERIFY_RESULT`, or `SSL_DN_FIELD`.
156    #[arg(help_heading = "Body parameters", long)]
157    _type: Type,
158
159    /// The value to use for the comparison. For example, the file type to
160    /// compare.
161    #[arg(help_heading = "Body parameters", long)]
162    value: String,
163}
164
165impl RuleCommand {
166    /// Perform command action
167    pub async fn take_action<C: CliArgs>(
168        &self,
169        parsed_args: &C,
170        client: &mut AsyncOpenStack,
171    ) -> Result<(), OpenStackCliError> {
172        info!("Create Rule");
173
174        let op = OutputProcessor::from_args(
175            parsed_args,
176            Some("load-balancer.l7policy/rule"),
177            Some("create"),
178        );
179        op.validate_args(parsed_args)?;
180
181        let mut ep_builder = create::Request::builder();
182
183        ep_builder.l7policy_id(&self.path.l7policy_id);
184
185        // Set body parameters
186        // Set Request.rule data
187        let args = &self.rule;
188        let mut rule_builder = create::RuleBuilder::default();
189        if let Some(val) = &args.admin_state_up {
190            rule_builder.admin_state_up(*val);
191        }
192
193        let tmp = match &args.compare_type {
194            CompareType::Contains => create::CompareType::Contains,
195            CompareType::EndsWith => create::CompareType::EndsWith,
196            CompareType::EqualTo => create::CompareType::EqualTo,
197            CompareType::Regex => create::CompareType::Regex,
198            CompareType::StartsWith => create::CompareType::StartsWith,
199        };
200        rule_builder.compare_type(tmp);
201
202        if let Some(val) = &args.invert {
203            rule_builder.invert(*val);
204        }
205
206        if let Some(val) = &args.key {
207            rule_builder.key(val);
208        }
209
210        if let Some(val) = &args.project_id {
211            rule_builder.project_id(val);
212        }
213
214        if let Some(val) = &args.tags {
215            rule_builder.tags(val.iter().map(Into::into).collect::<Vec<_>>());
216        }
217
218        if let Some(val) = &args.tenant_id {
219            rule_builder.tenant_id(val);
220        }
221
222        let tmp = match &args._type {
223            Type::Cookie => create::Type::Cookie,
224            Type::FileType => create::Type::FileType,
225            Type::Header => create::Type::Header,
226            Type::HostName => create::Type::HostName,
227            Type::Path => create::Type::Path,
228            Type::SslConnHasCert => create::Type::SslConnHasCert,
229            Type::SslDnField => create::Type::SslDnField,
230            Type::SslVerifyResult => create::Type::SslVerifyResult,
231        };
232        rule_builder._type(tmp);
233
234        rule_builder.value(&args.value);
235
236        ep_builder.rule(
237            rule_builder
238                .build()
239                .wrap_err("error preparing the request data")?,
240        );
241
242        let ep = ep_builder
243            .build()
244            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
245
246        let data: serde_json::Value = ep.query_async(client).await?;
247
248        op.output_single::<response::create::RuleResponse>(data.clone())?;
249        // Show command specific hints
250        op.show_command_hint()?;
251        Ok(())
252    }
253}