Pass Ansible variables into custom Ansible module

398 Views Asked by At

I have a custom module that resides in the library/ directory of my Ansible role. I can call the module from within my playbook, and the code executes correctly, but only if the values it expects are hardcoded in the module code itself. How can I pass values to the module from the playbook?

I've tried the following:

- name: Create repo and use specific KMS key
  ecr_kms:
    repositoryName: "new-ecr-repo"
    encryptionConfiguration.kmsKey: 'my-kms-key-id"

and

- name: Create repo and use specific KMS key
  ecr_kms:
    repositoryName: "{{ repo_name }}"
    encryptionConfiguration.kmsKey: "{{ kms_key_id }}"

Which I would expect to work, but neither does and, I get the following errors:

botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid length for parameter repositoryName, value: 0, valid min length: 2
Invalid length for parameter encryptionConfiguration.kmsKey, value: 0, valid min length: 1

The service module I'm trying to use

The code of the custom module:

#!/usr/bin/python

from urllib import response
import boto3
from jinja2 import Template
from ansible.module_utils.basic import AnsibleModule

def create_repo():
    client = boto3.client('ecr')

    response = client.create_repository(
        #registryId='',
        repositoryName='',
        imageTagMutability='IMMUTABLE',
        imageScanningConfiguration={
            'scanOnPush': True
        },
        encryptionConfiguration={
            'encryptionType': 'KMS',
            'kmsKey': ""
        }
    )



def main():
    create_repo()

if __name__ in '__main__':
    main()
1

There are 1 best solutions below

0
On BEST ANSWER

You do need to make your module aware of the arguments you want it to accept, so, in your main function:

#!/usr/bin/env python
from ansible.module_utils.basic import AnsibleModule


def create_repo(repositoryName, kmsKey):
  # Call to the API comes here


def main():
  module = AnsibleModule(
    argument_spec = dict(
      repositoryName = dict(type = 'str', required = True),
      kmsKey = dict(type = 'str', required = True),
    )
  )

  params = module.params
  
  create_repo(
    params['repositoryName'], 
    params['kmsKey']
  )


if __name__ == '__main__':
    main()

More can be found in the relevant documentation: Argument spec.


With this, your taks would be:

- name: Create repo and use specific KMS key
  ecr_kms:
    repositoryName: "{{ repo_name }}"
    kmsKey: "{{ kms_key_id }}"

PS, word of advice: avoid using a dot in a YAML key, that would just be making your life complicated for no actual good reason.