I'm new to Ansible, here I created a module which takes CSV as an argument like below: But it keep throwing error that it's not able to find CSV_TEST.csv file. am I creating it the right way as a variable in the ansible module?
module.py
def main():
field = dict(
csv=dict(type='str', required=True)
)
result = dict(
changed=False,
response='')
module = AnsibleModule(argument_spec=field)
csvFile = module.params['csv']
listFinal = list()
final = list()
if csvFile:
with open(csvFile, "r", newline='', encoding='utf-8-sig') as csvImport:
reader = csv.DictReader(csvImport)
for row in reader:
newDict = dict({
'name': row.get("Name"),
'address': row.get("Address")
'val': row.get("Val")
})
listFinal.append(newDict)
if listFinal:
for entry in listFinal:
if entry.get("val") == "Incorrect":
name = entry.get('name')
add = entry.get('address')
update = f'set add {add} of {name}'
final.append(update)
result['final'] = final
module.exit_json(changed=False, meta=result)
if __name__ == '__main__':
main()
Playbook.yml
---
- name: Test Variables with Ansible
hosts: localhost
vars:
x: 30
xName: "Sai"
gather_facts: false
become: false
tasks:
- name: Test Device Validation
portDescription:
csv: CSV_TEST.csv
register: result
- debug: var=result
The error is:
***
FileNotFoundError: [Errno 2] No such file or directory: 'CSV_TEST.csv'
fatal: [localhost]: FAILED! => {
"changed": false,
"module_stderr": "Shared connection to localhost closed.\r\n",
***
Can someone please suggest, what am I doing wrong here? CSV_TEST.csv is under the same tree structure (parent folder) like Playbook.yml
I think that if you have a relative file path in Ansible, Ansible will look in the local directory first (that is whatever directory is output if you run ran ansible from) then it looks in some other locations (check out the role directory structure for info on that).
So in my mind your directory structure is like
And I think you are running ansible like
ansible-playbook playbook.yml
from insideWorkingDir
. It can't findCSV_TEST.csv
because it's looking inWorkingDir
.If inside the python you have to put
Ansible/CSV_TEST.csv
then you also have to putAnsible/CSV_TEST.csv
in your playbook. SoIf this doesn't help then can you write out the directory structure in a text format and show where everything is executed from and where python is running (what
os.getcwd()
outputs)?