问题
SonarQube allows the upload of a profile.xml file via form-data POST request as follows:
curl -u admin:admin -X POST http://sonar:9000/qualityprofiles/restore -F backup=@profile.xml
I'm trying to translate this curl command into Ansible, using the uri module. Unfortunately, I don't see any chance to map the -F form-data option and the parameter backup to Ansible. Here's my attempt:
- name: create quality profile
uri:
url: "{{ sonar_api_url }}/qualityprofiles/restore"
method: POST
body: "{{ lookup('file', 'profile.xml') }}"
user: "{{ sonar_admin_user }}"
password: "{{ sonar_admin_pass }}"
force_basic_auth: "yes"
status_code: 200
I've also tried something like this:
body: "backup={{ lookup('file', 'profile.xml') }}"
Or just like this:
body: "backup=profile.xml"
But all without success. I keep getting the error "A backup file must be provided". Any ideas how this can be achieved?
回答1:
I also tried many options with the Ansible uri command with no luck despite being able to use the API via uri for things like setting Authentication etc.
I did succeed however using a parameterised shell: curl command:
Set Vars:
vars:
sonar_api_url: "https://yoursonarqubeserver.com/api"
sonar_token: "YourSonarQubeApiTokenThatRequiresAdminRights"
sonar_profile: "YourSonarQubeProfileToLoad.xml"
Task:
- name: POST a SonarQube Profile xml via curl
shell: 'curl -X "POST" "{{ sonar_api_url }}/qualityprofiles/restore" \
-H "Content-Type: multipart/form-data; charset=utf-8; boundary=__X_PAW_BOUNDARY__" \
-u {{ sonar_token }}: \
-k \
--form backup=@{{ sonar_profile }}'
Note the API token is passed in as the username with a plank password via the curl -u.
I also have a sample GitHub repo with a working example you can refer to.
回答2:
Lookups occur on the local computer, not on the remote computer (link), So maybe when you run your playbook on a remote machine it cant find the file... (template won't help for it puts the file in the target machine)
You can read the file contents into a variable as a pre-action (using cat..) and than use that var in the body property of the URI module.
来源:https://stackoverflow.com/questions/43042647/how-to-use-the-ansible-uri-module-to-post-a-file-as-form-data