diff --git a/config/data_source_config_common_functions.go b/config/data_source_config_common_functions.go deleted file mode 100644 index eb9afba..0000000 --- a/config/data_source_config_common_functions.go +++ /dev/null @@ -1,294 +0,0 @@ -package config - -import ( - "encoding/csv" - "encoding/json" - "fmt" - "io" - "strings" - - "github.com/360EntSecGroup-Skylar/excelize/v2" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "gopkg.in/yaml.v2" -) - -func dataSourceFilterSchema() *schema.Schema { - return &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - }, - "values": { - Type: schema.TypeList, - Required: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }, - }, - } -} - -func dataSourceLookupSchema() *schema.Schema { - return &schema.Schema{ - Type: schema.TypeSet, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "column": { - Type: schema.TypeString, - Required: true, - }, - "excel": { - Type: schema.TypeString, - Optional: true, - }, - "password": { - Type: schema.TypeString, - Optional: true, - }, - "worksheet": { - Type: schema.TypeString, - Optional: true, - }, - "yaml": { - Type: schema.TypeString, - Optional: true, - }, - "json": { - Type: schema.TypeString, - Optional: true, - }, - "key_column": { - Type: schema.TypeString, - Required: true, - }, - "value_column": { - Type: schema.TypeString, - Required: true, - }, - }, - }, - } -} - -func buildConfigDataSourceFilters(set *schema.Set) []map[string]interface{} { - var filters []map[string]interface{} - for _, v := range set.List() { - m := v.(map[string]interface{}) - var filterValues []string - for _, e := range m["values"].([]interface{}) { - filterValues = append(filterValues, fmt.Sprintf("%v", e)) - } - mvalue := make(map[string]interface{}) - mvalue["Name"] = m["name"].(string) - mvalue["Values"] = filterValues - filters = append(filters, mvalue) - } - return filters -} - -func buildConfigDataSourceLookup(set *schema.Set) ([]map[string]interface{}, error) { - var lookup []map[string]interface{} - for _, v := range set.List() { - m := v.(map[string]interface{}) - mvalue := make(map[string]interface{}) - mvalue["Column"] = m["column"].(string) - - source := 0 - if m["worksheet"].(string) != "" { - source++ - } - if m["json"].(string) != "" { - source++ - } - if m["yaml"].(string) != "" { - source++ - } - if source > 1 { - return nil, fmt.Errorf("only 1 type of lookup source is required (worksheet/json/yaml)") - } - - if m["worksheet"].(string) != "" { - if m["excel"].(string) != "" { - mvalue["Excel"] = m["excel"].(string) - } - if m["password"].(string) != "" { - mvalue["Password"] = m["password"].(string) - } - mvalue["Worksheet"] = m["worksheet"].(string) - } else { - mvalue["Excel"] = nil - mvalue["Worksheet"] = nil - mvalue["Password"] = nil - } - if m["json"].(string) != "" { - mvalue["Json"] = m["json"].(string) - } else { - mvalue["Json"] = nil - } - if m["yaml"].(string) != "" { - mvalue["Yaml"] = m["yaml"].(string) - } else { - mvalue["Yaml"] = nil - } - - mvalue["Key"] = m["key_column"].(string) - mvalue["Value"] = m["value_column"].(string) - lookup = append(lookup, mvalue) - } - return lookup, nil -} - -func checkLookupValue(lookup []map[string]interface{}, key string) bool { - for _, lv := range lookup { - if lv["Column"].(string) == key { - return true - } - } - return false -} - -func getLookupValue(lookup []map[string]interface{}, default_excel string, default_password string, default_worksheet string, key string, value string) (string, error) { - var lookupValue = "" - for _, lv := range lookup { - if lv["Column"].(string) == key { - // added json and yaml as source lookup - if lv["Json"] != nil { - jd, _ := stringToInterface(lv["Json"].(string)) - jsondata := jd.(map[interface{}]interface{}) - if jsondata[value] != nil { - lookupValue = jsondata[value].(string) - } else { - lookupValue = "" - } - } else if lv["Yaml"] != nil { - yd, _ := stringToInterface(lv["Yaml"].(string)) - yamldata := yd.(map[interface{}]interface{}) - if yamldata[value] != nil { - lookupValue = yamldata[value].(string) - } else { - lookupValue = "" - } - } else if lv["Worksheet"] != nil { - excel_file := default_excel - excel_pass := default_password - // added external excel file as source lookup - if lv["Excel"] != nil { - excel_file = lv["Excel"].(string) - } - // added property for password protected Excel worksheet - if lv["Password"] != nil { - excel_pass = lv["Password"].(string) - } - f, err := excelize.OpenFile(excel_file, excelize.Options{Password: excel_pass}) - if err != nil { - return "", err - } - worksheet := "" - if lv["Worksheet"].(string) != "" { - worksheet = lv["Worksheet"].(string) - } else { - worksheet = default_worksheet - } - rows, err := f.GetRows(worksheet) - if err != nil { - return "", fmt.Errorf(fmt.Sprintf("%v", rows)) - } - - columns := len(rows[0]) - - // get column of key - header := rows[0] - column_key := 0 - column_value := -1 - for i := 0; i < columns; i++ { - if header[i] == key { - column_key = i - } - if header[i] == lv["Value"] { - column_value = i - } - } - // get row of key - if column_value >= 0 { - for _, row := range rows { - if row[column_key] == value { - lookupValue = row[column_value] - } - } - } else { - lookupValue = "" - } - } else { - lookupValue = "" - } - } - } - return lookupValue, nil -} - -func checkFiltersForItem(filters []map[string]interface{}, key string, value string) bool { - for _, fv := range filters { - if fv["Name"] == key { - for _, d := range fv["Values"].([]string) { - if d == value { - return true - } - } - } - } - return false -} - -func stringInList(s string, list []string) bool { - for _, b := range list { - if b == s { - return true - } - } - return false -} - -func stringToInterface(s string) (interface{}, error) { - var v interface{} - - // Try if the string is yaml - err := yaml.Unmarshal([]byte(s), &v) - if err != nil { - // Try if the string is json - err = json.Unmarshal([]byte(s), &v) - if err != nil { - return nil, fmt.Errorf("unable to parse string using yaml or json") - } - } - return v, nil -} - -func stringToMap(s string) ([]map[string]string, error) { - r := csv.NewReader(strings.NewReader(s)) - rows := []map[string]string{} - var header []string - for { - record, err := r.Read() - if err == io.EOF { - break - } - if err != nil { - return nil, err - } - if header == nil { - header = record - } else { - dict := map[string]string{} - for i := range header { - dict[header[i]] = record[i] - } - rows = append(rows, dict) - } - } - return rows, nil -} diff --git a/config/data_source_configuration_workbook.go b/config/data_source_configuration_workbook.go index 1a27849..6aed52e 100644 --- a/config/data_source_configuration_workbook.go +++ b/config/data_source_configuration_workbook.go @@ -14,6 +14,24 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) +type ConfigurationWorkbook struct { + csv_string string + config_schema string + excel_file string + excel_pass string + sheet_name string + sheet_headers []interface{} + start_column string + end_column string + configuration_item string + col_config_item string + orientation string + filters []map[string]interface{} + lookup []map[string]interface{} + mapping interface{} + csv []map[string]string +} + func dataSourceConfigurationWorkbook() *schema.Resource { return &schema.Resource{ ReadContext: dataSourceConfigurationItemRead, @@ -78,119 +96,118 @@ func dataSourceConfigurationWorkbook() *schema.Resource { func dataSourceConfigurationItemRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { var diags diag.Diagnostics - // get all arguments passed to the resource - csv_string := d.Get("csv").(string) - config_schema := d.Get("schema").(string) - configuration_item := d.Get("configuration_item").(string) - col_config_item := d.Get("col_config_item").(string) - excel_file := d.Get("excel").(string) - excel_pass := d.Get("password").(string) - sheet_name := d.Get("worksheet").(string) - sheet_headers := d.Get("headers").([]interface{}) - orientation := d.Get("orientation").(string) - start_column := d.Get("col_start").(string) - end_column := d.Get("col_end").(string) - - var filters []map[string]interface{} + params := new(ConfigurationWorkbook) + params.csv_string = d.Get("csv").(string) + params.config_schema = d.Get("schema").(string) + params.configuration_item = d.Get("configuration_item").(string) + params.col_config_item = d.Get("col_config_item").(string) + params.excel_file = d.Get("excel").(string) + params.excel_pass = d.Get("password").(string) + params.sheet_name = d.Get("worksheet").(string) + params.sheet_headers = d.Get("headers").([]interface{}) + params.orientation = d.Get("orientation").(string) + params.start_column = d.Get("col_start").(string) + params.end_column = d.Get("col_end").(string) + // gather all filters if v, ok := d.GetOk("filter"); ok { - filters = buildConfigDataSourceFilters(v.(*schema.Set)) + params.filters = buildConfigDataSourceFilters(v.(*schema.Set)) } - var lookup []map[string]interface{} // gather all lookups if v, ok := d.GetOk("lookup"); ok { - lkp, err := buildConfigDataSourceLookup(v.(*schema.Set)) + var err error + params.lookup, err = buildConfigDataSourceLookup(v.(*schema.Set)) if err != nil { return diag.FromErr(err) } - lookup = lkp } // set the default configuration item column name - if col_config_item == "" { - col_config_item = "configuration_item" + if params.col_config_item == "" { + params.col_config_item = "configuration_item" } // set default value for configuration_item - if configuration_item == "" && sheet_name != "" { - configuration_item = sheet_name + if params.configuration_item == "" && params.sheet_name != "" { + params.configuration_item = params.sheet_name } // ###### Start Validations ###### // make sure csv or excel is used - if csv_string == "" && excel_file == "" { + if params.csv_string == "" && params.excel_file == "" { return diag.FromErr(fmt.Errorf(fmt.Sprintf("%v", "Must use csv or excel on the resource"))) } // make sure csv and excel is not on the same resource - if csv_string != "" && excel_file != "" { + if params.csv_string != "" && params.excel_file != "" { return diag.FromErr(fmt.Errorf(fmt.Sprintf("%v", "Cannot use csv and excel on the same resource"))) } - orientation = strings.ToLower(orientation) + params.orientation = strings.ToLower(params.orientation) valid_vertical_orientation := []string{"vertical", "vert", "v"} valid_horizontal_orientation := []string{"horizontal", "horiz", "h"} - if stringInList(orientation, valid_vertical_orientation) { - orientation = "vertical" - } else if stringInList(orientation, valid_horizontal_orientation) { - orientation = "horizontal" + if stringInList(params.orientation, valid_vertical_orientation) { + params.orientation = "vertical" + } else if stringInList(params.orientation, valid_horizontal_orientation) { + params.orientation = "horizontal" } else { return diag.FromErr(fmt.Errorf(fmt.Sprintf("%v", "Invalid type. Valid values are horizontal,vertical"))) } - if orientation == "vertical" && configuration_item == "" { + if params.orientation == "vertical" && params.configuration_item == "" { return diag.FromErr(fmt.Errorf(fmt.Sprintf("%v", "configuration_item is required if type is vertical"))) } - if orientation == "vertical" && csv_string != "" { + if params.orientation == "vertical" && params.csv_string != "" { return diag.FromErr(fmt.Errorf(fmt.Sprintf("%v", "vertical orientation is only valid for excel"))) } // ###### End Validations ###### // check if excel is being used - if excel_file != "" { - csvstring, err := excelToCSV(excel_file, excel_pass, sheet_name, sheet_headers, start_column, end_column, configuration_item, col_config_item, orientation) + if params.excel_file != "" { + csvstring, err := excelToCSV(params) if err != nil { return diag.FromErr(fmt.Errorf(fmt.Sprintf("%v", csvstring))) } - csv_string = csvstring + params.csv_string = csvstring // return diag.FromErr(fmt.Errorf(fmt.Sprintf("%v", csvstring))) } - if csv_string != "" { + if params.csv_string != "" { // convert the csv to map - // var csv []map[string]string - csv, err := stringToMap(csv_string) + csv, err := stringToMap(params.csv_string) if err != nil { return diag.FromErr(err) } + params.csv = csv // get all unique configuration items - items := unique(getConfigurationItems(csv, col_config_item)) + items := unique(getConfigurationItems(params.csv, params.col_config_item)) // convert the schema to map var map_yaml interface{} - if config_schema != "" { - map_yaml, err = stringToInterface(config_schema) + if params.config_schema != "" { + map_yaml, err = stringToInterface(params.config_schema) if err != nil { return diag.FromErr(err) } } else { - map_yaml, err = createDefaultMapping(items, csv, col_config_item) + map_yaml, err = createDefaultMapping(items, params.csv, params.col_config_item) if err != nil { return diag.FromErr(err) } } mapping := map_yaml.(map[interface{}]interface{}) + params.mapping = mapping["config_schema"] // remap all csv headers based on mapping configuration - records := reMapData(csv, mapping["config_schema"], filters, lookup, excel_file, excel_pass, sheet_name, col_config_item) + records := reMapData(params) // get the transformed data - data := getItemData(records, items, col_config_item) + data := getItemData(records, items, params.col_config_item) // set the data to the attribute json if err := d.Set("json", data); err != nil { @@ -198,10 +215,10 @@ func dataSourceConfigurationItemRead(ctx context.Context, d *schema.ResourceData } } else { // set the data to the attribute json - if configuration_item == "" { - configuration_item = sheet_name + if params.configuration_item == "" { + params.configuration_item = params.sheet_name } - if err := d.Set("json", "{\""+configuration_item+"\": []}"); err != nil { + if err := d.Set("json", "{\""+params.configuration_item+"\": []}"); err != nil { return diag.FromErr(err) } } @@ -211,34 +228,34 @@ func dataSourceConfigurationItemRead(ctx context.Context, d *schema.ResourceData return diags } -func excelToCSV(excel_file string, excel_pass string, sheet_name string, sheet_headers []interface{}, start_column string, end_column string, configuration_item string, col_config_item string, orientation string) (string, error) { +func excelToCSV(args *ConfigurationWorkbook) (string, error) { var row_arr = []string{ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", } min := 0 max := len(row_arr) - 1 - if start_column != "" { - min = sliceIndex(row_arr, start_column) + if args.start_column != "" { + min = sliceIndex(row_arr, args.start_column) if min == -1 { min = 0 } } - if end_column != "" { - max = sliceIndex(row_arr, end_column) + if args.end_column != "" { + max = sliceIndex(row_arr, args.end_column) if max == -1 { max = len(row_arr) - 1 } } var csv = []string{} - f, err := excelize.OpenFile(excel_file, excelize.Options{Password: excel_pass}) + f, err := excelize.OpenFile(args.excel_file, excelize.Options{Password: args.excel_pass}) if err != nil { return "", err } // Get all rows - rows, err := f.GetRows(sheet_name) + rows, err := f.GetRows(args.sheet_name) if err != nil { return "", fmt.Errorf(fmt.Sprintf("%v", rows)) } @@ -246,12 +263,12 @@ func excelToCSV(excel_file string, excel_pass string, sheet_name string, sheet_h // get the number of columns row_len := len(rows[0]) - if orientation == "horizontal" { + if args.orientation == "horizontal" { // check if configuration item is in the column names config_item_exist := false for i := 0; i < row_len; i++ { if (i >= min) && (i <= max) && (i < row_len) { - if (rows[0][i] == "configuration_item") || (rows[0][i] == col_config_item) { + if (rows[0][i] == "configuration_item") || (rows[0][i] == args.col_config_item) { config_item_exist = true } } @@ -265,7 +282,7 @@ func excelToCSV(excel_file string, excel_pass string, sheet_name string, sheet_h if idx == 0 && i == min { sb.WriteString("\"configuration_item\",") } else if idx > 0 && i == min { - sb.WriteString("\"" + configuration_item + "\",") + sb.WriteString("\"" + args.configuration_item + "\",") } } @@ -274,8 +291,8 @@ func excelToCSV(excel_file string, excel_pass string, sheet_name string, sheet_h } else { // replace with supplied header if idx == 0 && i > min { - if len(sheet_headers) > 0 && i <= len(sheet_headers) { - sb.WriteString("\"" + sheet_headers[i-1].(string) + "\"") + if len(args.sheet_headers) > 0 && i <= len(args.sheet_headers) { + sb.WriteString("\"" + args.sheet_headers[i-1].(string) + "\"") } else { sb.WriteString("\"" + row[i] + "\"") } @@ -320,7 +337,7 @@ func excelToCSV(excel_file string, excel_pass string, sheet_name string, sheet_h csv = append(csv, sb.String()) for i := 1; i < maxcol; i++ { sb.Reset() - sb.WriteString("\"" + configuration_item + "\",") + sb.WriteString("\"" + args.configuration_item + "\",") for idx, row := range rows { if i > len(row)-1 { if idx < len(rows)-1 { @@ -416,12 +433,12 @@ func unique(items []string) []string { return list } -func reMapData(csv []map[string]string, mapping interface{}, filters []map[string]interface{}, lookup []map[string]interface{}, excel_file string, excel_pass string, worksheet string, configuration_item string) []map[string]interface{} { - new_csv := make([]map[string]interface{}, len(csv)) - for key, value := range csv { +func reMapData(args *ConfigurationWorkbook) []map[string]interface{} { + new_csv := make([]map[string]interface{}, len(args.csv)) + for key, value := range args.csv { item_key := "" for k, v := range value { - if k == configuration_item { + if k == args.configuration_item { item_key = v } } @@ -433,7 +450,7 @@ func reMapData(csv []map[string]string, mapping interface{}, filters []map[strin for k, v := range value { _ = v if strings.HasPrefix(k, "attr") { - new_key, new_type = getMapValue(mapping, item_key, k) + new_key, new_type = getMapValue(args.mapping, item_key, k) if new_key != "" { if new_type == "string" { new_value[new_key] = value[k] @@ -459,7 +476,7 @@ func reMapData(csv []map[string]string, mapping interface{}, filters []map[strin new_value[new_key] = value[k] } } - } else if k == configuration_item { + } else if k == args.configuration_item { new_value[k] = value[k] } else if strings.HasPrefix(k, "s_") || strings.HasPrefix(k, "string_") { replacer := strings.NewReplacer("s_", "", "string_", "") @@ -523,11 +540,11 @@ func reMapData(csv []map[string]string, mapping interface{}, filters []map[strin } // get lookup value - if lookup != nil && checkLookupValue(lookup, new_key) { + if args.lookup != nil && checkLookupValue(args.lookup, new_key) { if strings.Contains(value[new_key], ",") { lkvals := strings.Split(value[new_key], ",") for idx, vl := range lkvals { - lookup_value, err := getLookupValue(lookup, excel_file, excel_pass, worksheet, new_key, vl) + lookup_value, err := getLookupValue(args.lookup, args.excel_file, args.excel_pass, args.sheet_name, new_key, vl) if err == nil && lookup_value != "" { if idx == 0 { new_value[new_key] = lookup_value @@ -537,7 +554,7 @@ func reMapData(csv []map[string]string, mapping interface{}, filters []map[strin } } } else { - lookup_value, err := getLookupValue(lookup, excel_file, excel_pass, worksheet, new_key, value[new_key]) + lookup_value, err := getLookupValue(args.lookup, args.excel_file, args.excel_pass, args.sheet_name, new_key, value[new_key]) if err == nil && lookup_value != "" { new_value[new_key] = lookup_value } @@ -545,12 +562,12 @@ func reMapData(csv []map[string]string, mapping interface{}, filters []map[strin } // check if value included in filter - if len(filters) > 0 { + if len(args.filters) > 0 { if !include_value { - include_value = checkFiltersForItem(filters, k, value[k]) + include_value = checkFiltersForItem(args.filters, k, value[k]) } if !include_value { - include_value = checkFiltersForItem(filters, new_key, value[k]) + include_value = checkFiltersForItem(args.filters, new_key, value[k]) } } else { include_value = true diff --git a/config/data_source_restapi_get.go b/config/data_source_restapi_get.go new file mode 100644 index 0000000..dc78d29 --- /dev/null +++ b/config/data_source_restapi_get.go @@ -0,0 +1,124 @@ +package config + +import ( + "context" + "encoding/base64" + "io/ioutil" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +type RequestParameters struct { + uri string + params []map[string]interface{} + headers []map[string]interface{} + user string + password string +} + +func dataSourceRestApiGet() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourceRestApiRead, + Schema: map[string]*schema.Schema{ + "uri": { + Type: schema.TypeString, + Required: true, + }, + "user": { + Type: schema.TypeString, + Optional: true, + }, + "password": { + Type: schema.TypeString, + Optional: true, + }, + "param": dataSourceKeyValueSchema(), + "header": dataSourceKeyValueSchema(), + "response": { + Type: schema.TypeString, + Optional: true, + Computed: true, + }, + }, + } +} + +func dataSourceRestApiRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + var diags diag.Diagnostics + + reqparm := new(RequestParameters) + reqparm.uri = d.Get("uri").(string) + reqparm.user = d.Get("user").(string) + reqparm.password = d.Get("password").(string) + + if v, ok := d.GetOk("param"); ok { + reqparm.params = buildConfigDataSourceParams(v.(*schema.Set)) + } + if v, ok := d.GetOk("header"); ok { + reqparm.headers = buildConfigDataSourceParams(v.(*schema.Set)) + } + + data, err := getRequest(reqparm) + if err != nil { + return diag.FromErr(err) + } + if e := d.Set("response", data); e != nil { + return diag.FromErr(e) + } + + d.SetId(strconv.FormatInt(time.Now().Unix(), 10)) + + return diags +} + +func getRequest(args *RequestParameters) (string, error) { + param := url.Values{} + for _, p := range args.params { + param.Add(p["Key"].(string), p["Value"].(string)) + } + + url := args.uri + if len(args.params) > 0 { + url = args.uri + "?" + param.Encode() + } + + method := "GET" + payload := strings.NewReader(``) + client := &http.Client{} + req, err := http.NewRequest(method, url, payload) + if err != nil { + return "", err + } + + // add basic authentication + if args.user != "" && args.password != "" { + plainCred := args.user + ":" + args.password + base64Cred := base64.StdEncoding.EncodeToString([]byte(plainCred)) + req.Header.Add("Authorization", "Basic "+base64Cred) + } + + // add headers + for _, h := range args.headers { + req.Header.Add(h["Key"].(string), h["Value"].(string)) + } + + // Send http request + response, err := client.Do(req) + if err != nil { + return "", err + } + + defer response.Body.Close() + responseData, err := ioutil.ReadAll(response.Body) + if err != nil { + return "", err + } + + return string(responseData), nil +} diff --git a/config/provider.go b/config/provider.go index 44fa605..8d19a93 100644 --- a/config/provider.go +++ b/config/provider.go @@ -8,7 +8,9 @@ func Provider() *schema.Provider { return &schema.Provider{ ResourcesMap: map[string]*schema.Resource{}, DataSourcesMap: map[string]*schema.Resource{ - "config_workbook": dataSourceConfigurationWorkbook(), + "config_workbook": dataSourceConfigurationWorkbook(), + "config_ini": dataSourceIni(), + "config_restapi_get": dataSourceRestApiGet(), }, } } diff --git a/docs/data-sources/ini.md b/docs/data-sources/ini.md new file mode 100644 index 0000000..c55e6ff --- /dev/null +++ b/docs/data-sources/ini.md @@ -0,0 +1,47 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "config_ini Data Source - terraform-provider-config" +subcategory: "" +description: This data source will parse the INI file and output a JSON string format. + +--- + +# config_ini (Data Source) + +### Example + +```terraform +data "config_ini" "cfg" { + ini = file("configuration.ini") +} + +data "config_ini" "cfg_str" { + ini = <<-EOT + [setup] + url=https://test.com + port=8443 + active=1 + EOT +} +``` + +### Example - Using with section + +```terraform +data "config_ini" "cfg" { + ini = file("configuration.ini") + section = "setup" +} +``` + + +## Properties + +- **ini** (String) - (Required) Content of the ini file. Use the `file` function to load the contents of the file. +- **section** (String) - (Optional) Select only a specific section + +### Output + +- **id** (String) The ID of this resource. +- **json** (String) - JSON value in string format. To use this in other resources, you must use the function `jsondecode`. + diff --git a/docs/data-sources/restapi_get.md b/docs/data-sources/restapi_get.md new file mode 100644 index 0000000..af893fd --- /dev/null +++ b/docs/data-sources/restapi_get.md @@ -0,0 +1,98 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "config_restapi_get Data Source - terraform-provider-config" +subcategory: "" +description: |- + +--- + +# config_restapi_get (Data Source) + +### Example + +```terraform +data "config_restapi_get "general" { + uri = "http://localhost:3000/posts" +} +``` + +### Example - Using with query parameters + +```terraform +data "config_restapi_get "general" { + uri = "http://localhost:3000/posts" + param { + key = "id" + value = "1" + } + param { + key = "author" + value = "typicode" + } +} +``` + +### Example - Using with basic authentication credentials + +```terraform +data "config_restapi_get "general" { + uri = "http://localhost:3000/posts" + user = "user" + password = "pass" +} + +#################################################### + +locals { + userpass = "${var.username}:${var.password}" +} +data "config_restapi_get "general" { + uri = "http://localhost:3000/posts" + header { + key = "Authorization" + value = "Basic ${base64encode(local.userpass)}" + } +} +``` + +### Example - Using with additional headers +```terraform +data "config_restapi_get "general" { + uri = "http://localhost:3000/posts" + header { + key = "Content-type" + value = "application/json" + } + header { + key = "Response-type" + value = "application/json" + } +} +``` + + +## Properties + +- **uri** (String) - (Required) URI of the target api. +- **user** (String) - (Optional) Username for basic authentication. +- **password** (String) - (Optional) Password for basic authentication. +- **param** (Block) - (Optional) URI parameters. +- **header** (Block) - (Optional) Additional headers for the request. + +### Param + +Nested `param` blocks have the following structure: +- **key** (String) - (Required) The name of the field to query. +- **value** (String) - (Required) The value to query. + +### Param + +Nested `header` blocks have the following structure: +- **key** (String) - (Required) The name of the header to add. +- **value** (String) - (Required) The value to header. + +### Output + +- **id** (String) The ID of this resource. +- **response** (String) - Response value in string format. + diff --git a/examples/files/config.json b/examples/configuration_workbook/files/config.json similarity index 100% rename from examples/files/config.json rename to examples/configuration_workbook/files/config.json diff --git a/examples/files/config.yaml b/examples/configuration_workbook/files/config.yaml similarity index 100% rename from examples/files/config.yaml rename to examples/configuration_workbook/files/config.yaml diff --git a/examples/files/data.xlsx b/examples/configuration_workbook/files/data.xlsx similarity index 100% rename from examples/files/data.xlsx rename to examples/configuration_workbook/files/data.xlsx diff --git a/examples/files/deployVM.csv b/examples/configuration_workbook/files/deployVM.csv similarity index 100% rename from examples/files/deployVM.csv rename to examples/configuration_workbook/files/deployVM.csv diff --git a/examples/configuration_workbook/files/event.ini b/examples/configuration_workbook/files/event.ini new file mode 100644 index 0000000..6042a43 --- /dev/null +++ b/examples/configuration_workbook/files/event.ini @@ -0,0 +1,5 @@ +[event] +B_INFM_CM_0013_D=/tmp/batch/scripts/B_INFM_CM_0013_D/scripts/B_INFM_CM_0013_D.sh +B_INFM_CM_0025_D=/tmp/batch/scripts/B_INFM_CM_0025_D/scripts/B_INFM_CM_0025_D.sh +B_INFM_CM_1054_D=/tmp/batch/scripts/B_INFM_CM_0054_D/scripts/B_INFM_CM_0054_D.sh +B_INFM_CM_1055_D=/tmp/batch/scripts/B_INFM_CM_0055_D/scripts/B_INFM_CM_0055_D.sh \ No newline at end of file diff --git a/examples/files/event.json b/examples/configuration_workbook/files/event.json similarity index 100% rename from examples/files/event.json rename to examples/configuration_workbook/files/event.json diff --git a/examples/files/event.xlsx b/examples/configuration_workbook/files/event.xlsx similarity index 100% rename from examples/files/event.xlsx rename to examples/configuration_workbook/files/event.xlsx diff --git a/examples/files/event.yaml b/examples/configuration_workbook/files/event.yaml similarity index 100% rename from examples/files/event.yaml rename to examples/configuration_workbook/files/event.yaml diff --git a/examples/files/test.csv b/examples/configuration_workbook/files/test.csv similarity index 100% rename from examples/files/test.csv rename to examples/configuration_workbook/files/test.csv diff --git a/examples/main.tf b/examples/configuration_workbook/main.tf similarity index 90% rename from examples/main.tf rename to examples/configuration_workbook/main.tf index 5ddb81e..1c56d70 100644 --- a/examples/main.tf +++ b/examples/configuration_workbook/main.tf @@ -61,13 +61,18 @@ data "config_workbook" "lookup" { } lookup { - yaml = file("files/event.yaml") + ini = file("files/event.ini") + section = "event" column = "dependents" key_column = "name" value_column = "script" } } +data "config_ini" "ini" { + ini = file("files/event.ini") +} + # output "horiz" { # value = jsondecode(data.config_workbook.excel.json) # } @@ -91,3 +96,7 @@ output "lookup" { # output "vm" { # value = jsondecode(data.config_workbook.vm.json) # } + +output "ini" { + value = jsondecode(data.config_ini.ini.json) +} \ No newline at end of file diff --git a/examples/restapi/main.tf b/examples/restapi/main.tf new file mode 100644 index 0000000..bd4b607 --- /dev/null +++ b/examples/restapi/main.tf @@ -0,0 +1,30 @@ +terraform { + required_providers { + config = { + version = "0.2.2" + source = "aa/test/config" + } + } +} + +provider "config" {} + +data "config_restapi_get" "test" { + uri = "http://localhost:3000/posts" + header { + key = "Content-Type" + value = "application/json" + } + param { + key = "id" + value = "1" + } + param { + key = "author" + value = "typicode" + } +} + +output "response" { + value = jsondecode(data.config_restapi_get.test.response) +}