Below is my build script (not using xcodebuild plugin).
In this answer, we add / remove your iOS certificate without manipulating the login keychain nor changing the default keychain by:
-T /usr/bin/codesign
Creates temporary keychain. I added the $$
which is the PID. This means we allow can parallelize the script by allowing multiple temporary keychains to be created concurrently:
# Create temp keychain
MY_KEYCHAIN="MyKeychain-$$.keychain"
MY_KEYCHAIN_PASSWORD="secret"
security create-keychain -p "$MY_KEYCHAIN_PASSWORD" "$MY_KEYCHAIN"
Appends temporary keychain to the search list. Be careful to use security list-keychains -s
to append your keychain, else, you will clobber builds running in another thread:
# Append keychain to the search list
security list-keychains -d user -s "$MY_KEYCHAIN" $(security list-keychains -d user | sed s/\"//g)
security list-keychains
Unlocks temporary keychain with no automatic relocking timeout (security set-keychain-settings
). If you forget to fix the relocking timeout, builds taking longer than the default relocking timeout will trigger the password prompt:
# Unlock the keychain
security set-keychain-settings "$MY_KEYCHAIN"
security unlock-keychain -p "$MY_KEYCHAIN_PASSWORD" "$MY_KEYCHAIN"
Import iOS certificate and grants /usr/bin/codesign
access without requiring a password prompt.
# Import certificate
security import $CERT -k "$MY_KEYCHAIN" -P "$CERT_PASSWORD" -T "/usr/bin/codesign"
Because we use a temporary keychain and we know that it contains only 1 certificate, we can, programmatically, derive the IOS_IDENTITY (required as an input to build steps).
# Detect the iOS identity
IOS_IDENTITY=$(security find-identity -v -p codesigning "$MY_KEYCHAIN" | head -1 | grep '"' | sed -e 's/[^"]*"//' -e 's/".*//')
IOS_UUID=$(security find-identity -v -p codesigning "$MY_KEYCHAIN" | head -1 | grep '"' | awk '{print $2}')
# New requirement for MacOS 10.12
security set-key-partition-list -S apple-tool:,apple: -s -k $MY_KEYCHAIN_PASSWORD $MY_KEYCHAIN
Do your build now
# Insert your custom build steps
Delete temporary keychain. Note, doing so, will automatically pop it from the search list. i.e. all other keychains will remain.
# Delete the temp keychain
security list-keychains
security delete-keychain "$MY_KEYCHAIN"
security list-keychains