Skip to content

Instantly share code, notes, and snippets.

@jjaniec
Last active November 3, 2021 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjaniec/f325a7fa7846440c54e86a22cba59983 to your computer and use it in GitHub Desktop.
Save jjaniec/f325a7fa7846440c54e86a22cba59983 to your computer and use it in GitHub Desktop.
Convert a roleMap (xpath /hudson/authorizationStrategy/roleMap) from a jenkins config.xml file to a yaml compatible with JCasC
#!/bin/bash
#set -o xtrace
# Usage: $0 ./path-of-config.xml
getxml() { # $1 = xml file, $2 = xpath expression
echo "cat $2" | xmllint --shell $1 |\
sed -n 's/[^\"]*\"\([^\"]*\)\"[^\"]*/\1/gp'
}
fmt_list_to_yaml() {
LIST=(${@})
for ((i = 0; i < ${#LIST[@]}; i++)) ;
do
echo " - \"${LIST[$i]}\""
done;
}
adapt_role_permissions() {
ROLE_PERMISSIONS=(${@})
for ((i = 0; i < ${#ROLE_PERMISSIONS[@]}; i++)) ;
do
PERM_CATEGORY=$(echo "${ROLE_PERMISSIONS[$i]}" | rev | cut -d '.' -f 2 | rev)
if [ "${PERM_CATEGORY}" = "CredentialsProvider" ];
then
PERM_CATEGORY="Credentials"
elif [ "${PERM_CATEGORY}" = "Computer" ];
then
PERM_CATEGORY="Agent"
elif [ "${PERM_CATEGORY}" = "Item" ];
then
PERM_CATEGORY="Job"
elif [ "${PERM_CATEGORY}" = "Hudson" ];
then
PERM_CATEGORY="Overall"
fi
PERM_ACTION=$(echo "${ROLE_PERMISSIONS[$i]}" | rev | cut -d '.' -f 1 | rev)
echo "${PERM_CATEGORY}/${PERM_ACTION}"
done;
}
main() {
eval ROLES=($(getxml "$1" "/hudson/authorizationStrategy/roleMap/role/@name" 2> /dev/null | sed -e 's/^\|$/"/g'))
for ((i = 0; i < ${#ROLES[@]}; i++)) ;
do
echo "# ${ROLES[$i]}";
ROLE_NAME="${ROLES[$i]}"
# Pattern
ROLE_PATTERN=$(getxml "${1}" "/hudson/authorizationStrategy/roleMap/role[@name='${ROLES[$i]}']/@pattern" 2> /dev/null)
# Assigned ids
ROLE_ASSIGNED_SIDS=($(cat config.xml | xmllint --xpath 'string(/hudson/authorizationStrategy/roleMap/role[@name='\""${ROLES[$i]}"\"']/assignedSIDs)' - 2>/dev/null | tr -d ' ' | sed -E '/^$/d'))
# Role permissions
ROLE_PERMISSIONS=($(cat config.xml | xmllint --xpath 'string(/hudson/authorizationStrategy/roleMap/role[@name='\""${ROLES[$i]}"\"']/permissions)' - 2>/dev/null | tr -d ' ' | sed -E '/^$/d'))
ROLE_PERMISSIONS_ADAPTED=($(adapt_role_permissions ${ROLE_PERMISSIONS[@]} | sort))
ROLE_ASSIGNED_SIDS_YAML="$(fmt_list_to_yaml ${ROLE_ASSIGNED_SIDS[@]})"
ROLE_PERMISSIONS_YAML="$(fmt_list_to_yaml ${ROLE_PERMISSIONS_ADAPTED[@]})"
if [ ${#ROLE_ASSIGNED_SIDS[@]} -eq 0 ];
then
ROLE_ASSIGNED_SIDS_YAML="[]"
else
ROLE_ASSIGNED_SIDS_YAML="
${ROLE_ASSIGNED_SIDS_YAML}"
fi;
if [ ${#ROLE_PERMISSIONS[@]} -eq 0 ];
then
ROLE_PERMISSIONS_YAML="[]"
else
ROLE_PERMISSIONS_YAML="
${ROLE_PERMISSIONS_YAML}"
fi;
ROLE_YAML_TPL=$(cat <<EOF
- name: "${ROLE_NAME}"
pattern: "${ROLE_PATTERN}"
permissions: ${ROLE_PERMISSIONS_YAML}
assignments: ${ROLE_ASSIGNED_SIDS_YAML}
EOF
)
echo "${ROLE_YAML_TPL}"
echo
done;
}
main $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment