ML
    • Recent
    • Categories
    • Tags
    • Popular
    • Users
    • Groups
    • Register
    • Login

    Random Generator Ansible Module

    IT Discussion
    ansible python module
    1
    1
    2.0k
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • stacksofplatesS
      stacksofplates
      last edited by stacksofplates

      Just practicing with some custom modules. I can't really think of anything useful to write because there are so many already, so I just made a random string generator that can be passed into a variable for other tasks.

      Here's the output:
      0_1499911061333_randomgen.png

      Here's the module:

      #!/usr/bin/python
      
      DOCUMENTATION='''
      ---
      module: random_generator
      short_description: Generates random string
      description:
          - Generates random string
          - from a given size
      options:
        size:
          description:
            - Size of the string to generate
          required: true
      '''
      RETURN = '''
      msg:
          description: Returns random string
          type: string
      '''
      EXAMPLES = '''
      - random_generator:
          size: 25
      '''
      
      import string
      import random 
      from ansible.module_utils.basic import AnsibleModule
      
      
      def random_generator(size, chars=string.ascii_uppercase + string.digits):
          return ''.join(random.choice(chars) for _ in range(size))
      
      module = AnsibleModule(
          argument_spec = dict(
          size = dict(required=True, type='int')
          )
      )
      size = module.params.get('size')
      
      try:
          random_generator(size)
          success = True
          ret_msg = str(random_generator(size))
      except KeyError:
         success = False
         ret_msg = "Error"
      
      if success:
          module.exit_json(msg=ret_msg)
      else:
          module.fail_json(msg=ret_msg)
      
      
      if __name__ == "__main__":
        main()
      

      Here's how the documentation looks:

      0_1499911179069_doc.png

      1 Reply Last reply Reply Quote 3
      • 1 / 1
      • First post
        Last post