Search code examples
sql-serveransibleansible-inventory

SQL Server database queries in Ansible


I would like to find out if anyone in the community has used Ansible to manipulate a Microsoft SQL Server database?

We want to add a task to our environment configuration scripts written in Ansible that will INSERT rows into a SQL Server table. The rows will have parameters that are specified in our variables files.

I have been unable to locate a specific Ansible module for achieving this so would like to hear if anyone has has success in some other way?


Solution

  • For completeness here is the syntax of the solution used in Ansible to SELECT & INSERT for Microsoft SQL Server:

    INSERT

    - name: 'insert row to SQL server DB'
      win_shell: "invoke-sqlcmd -username \"{{db_user}}\" -password \"{{db_pass}}\" -Query \"INSERT INTO Addresses (DoorNum,Street,Town,PostCode) VALUES ({{ item.doornum }},'{{ item.street }}','{{ item.town }}''{{ item.postcode }}')\""
    

    SELECT

    - name: 'select from SQL server DB'
      win_shell: "invoke-sqlcmd -username \"{{db_user}}\" -password \"{{db_pass}}\" -Query \"SELECT ID FROM Addresses WHERE PostCode = '{{ item.postcode }}'\" | Select-Object * -ExcludeProperty ItemArray, Table, RowError, RowState, HasErrors | ConvertTo-Json"
      register: response
    
    - set_fact:
        ids: "{{ response.stdout|from_json}}"
    
    - debug:
        var: ids