简体   繁体   中英

Sorting of strings variable in ansible playbook and display result in asending order

I have list of variable like, item-1, item-22, item-3, item-99 i need to display as result of ansible playbook in following form

item-1, item-3, item-22, item-99.

I tried with below syntax but no luck.

- set_fact:
      sorted_list_values: "{{ cluster_info | sort }}"

also I created one library folder and inside that i tried to written python module and tried to refer in ansible playbook but it gives me indention error.

#!/usr/bin/python
import json
from ansible.module_utils.basic import *
import sysy
def main():

        module = AnsibleModule(
                 argument_spec = dict(
                        var1   = dict(required=True, type='str'),
                        var2   = dict(required=True, type='str'),
                        var3   = dict(required=True, type='str'),
                        var4   = dict(required=True, type='str'),
                 )
        )

                var1 = module.params['var1']
                var2 = module.params['var2']
                var3 = module.params['var3']
                var4 = module.params['var4']

               dict1 = OrderedDict(sorted(dict.items()))

            module.exit_json(changed=False, meta=response)


if __name__ == '__main__':
    main()

actually i am novice in python.

Any link or guidance would be really appreciated to sort strings variable and display as ansible playbook resilt. Thanks

I used another trick, sorted it with help of Golan sort program.

Sorting with Golang

package main
import (
         "fmt" "sort" "os"
)
func main() {
     cmd := os.Args[1:]
     sort.Strings(cmd)
     fmt.Println(cmd)
}

cat site.yaml

---
- hosts: localhost
  connection: local
  gather_facts: false

  vars:
    var1: "{{ clus_var1 }}"
    var2: "{{ clus_var2 }}"
    var3: "{{ clus_var3 }}"
    var4: "{{ clus_var4 }}"

  tasks:
    - shell: "go run /etc/ansible/gosave/sort.go {{ var1 }} {{ var2 }} {{ var3}} {{ var4 }}"
      register: result
    - debug:
         var: result.stdout

run ansible-playbook site.yaml --extra-vars "clus_var1=cluster-2 clus_var2=cluster-99 clus_var3=cluster-1 clus_var4=cluster-5"

o/p as [cluster-1 cluster-2 cluster-5 cluster-99]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM